现代c++标准库中vector容器的emplace_back方法
一言以蔽之,emplace_back
是c++11引入的vector成员函数,用于在vector末尾直接构造元素,而不是先构造再拷贝或移动
基本用法
1 2
| std::vector<MyClass>vec; vec.emplace_back(args...);
|
与push_back的区别
- 构造方式
push_back
:先构造临时对象,然后拷贝或移动到容器中
emplace_back
:直接在容器内存中构造对象
- 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; std::cout << "Using push_back:\n"; people.push_back(Person("Alice", 30)); std::cout << "\nUsing emplace_back:\n"; people.emplace_back("Bob", 25); return 0; }
|