1. 程式人生 > >你想知道的 std::vector::push_back 和 std::vector::emplace_back

你想知道的 std::vector::push_back 和 std::vector::emplace_back

## 引言 C++ 11 後,標準庫容器 `std::vector` 包含了成員函式 `emplace` 和 `emplace_back`。`emplace` 在容器指定位置插入元素,`emplace_back` 在容器末尾新增元素。 `emplace` 和 `emplace_back` 原理類似,本文僅討論 `push_back` 和 `emplace_back`。 ## 定義 首先看下 Microsoft Docs 對 `push_back` 和 `emplace_back` 的定義: - `push_back`:Adds an element to the end of the vector. - `emplace_back`:Adds an element **constructed in place** to the end of the vector. 兩者的定義我用了加粗字型作區分,那麼現在問題就在於什麼叫做 **constructed in place** ? 再來看下官方文件(www.cplusplus.com)怎麼介紹 `emplace_back` 的: > t