JiaHeng-DLUT
8/12/2019 - 4:42 AM

emplace_back() and push_back()

  • emplace_backpush_back 都是向容器内添加数据

  • 对于在容器中添加类的对象时,相比于 push_backemplace_back 可以避免额外的类的复制和移动操作

  • "emplace_back avoids the extra copy or move operation required when using push_back."

  • std::vector<T,Allocator>::emplace_back


版权声明:本文为CSDN博主「SpikeKing」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/caroline_wendy/article/details/12967193

#include <vector>
#include <string>
#include <iostream>
using namespace std;

struct President {
	string name;
	string country;
	int year;

	President(string p_name, string p_country, int p_year)
		: name(move(p_name)), country(move(p_country)), year(p_year) {
		cout << "I am being constructed.\n";
	}
	President(President&& other)
		: name(move(other.name)), country(move(other.country)), year(other.year) {
		cout << "I am being moved.\n";
	}
	President& operator=(const President& other) = default;
};

int main() {
	vector<President> elections;
	cout << "emplace_back:\n";
	elections.emplace_back("Nelson Mandela", "South Africa", 1994);

	vector<President> reElections;
	cout << "\npush_back:\n";
	reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));

	cout << "\nContents:\n";
	for (President const& president : elections) {
		cout << president.name << " was elected president of " << president.country << " in " << president.year << ".\n";
	}
	for (President const& president : reElections) {
		cout << president.name << " was re-elected president of " << president.country << " in " << president.year << ".\n";
	}
}