现代c++vector的emplace_back成员函数

现代c++标准库中vector容器的emplace_back方法

一言以蔽之,emplace_back是c++11引入的vector成员函数,用于在vector末尾直接构造元素,而不是先构造再拷贝或移动

基本用法

1
2
std::vector<MyClass>vec;
vec.emplace_back(args...);

与push_back的区别

  1. 构造方式
    • push_back:先构造临时对象,然后拷贝或移动到容器中
    • emplace_back:直接在容器内存中构造对象
  2. emplace_back更高效

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <vector>
#include <string>
#include <iostream>

class Person {
public:
Person(std::string name, int age) : name_(name), age_(age) {
std::cout << "Constructing " << name_ << "\n";
}

Person(const Person& other) : name_(other.name_), age_(other.age_) {
std::cout << "Copying " << name_ << "\n";
}

Person(Person&& other) noexcept : name_(std::move(other.name_)), age_(other.age_) {
std::cout << "Moving " << name_ << "\n";
}

private:
std::string name_;
int age_;
};

int main() {
std::vector<Person> people;

// 使用push_back
std::cout << "Using push_back:\n";
people.push_back(Person("Alice", 30));
// 输出:
// Constructing Alice (临时对象)
// Moving Alice (移动到vector中)

// 使用emplace_back
std::cout << "\nUsing emplace_back:\n";
people.emplace_back("Bob", 25);
// 输出:
// Constructing Bob (直接在vector中构造)

return 0;
}

现代c++vector的emplace_back成员函数
http://example.com/2025/04/27/现代c-vector的emplace-back成员函数/
作者
John Doe
发布于
2025年4月27日
许可协议