c_cpp emplace_back()和push_back()

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp emplace_back()和push_back()相关的知识,希望对你有一定的参考价值。

#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";
	}
}

以上是关于c_cpp emplace_back()和push_back()的主要内容,如果未能解决你的问题,请参考以下文章

[CPP]push_back和emplace_back的区别

push_back和emplace_back的区别

在C++里,emplace_back可以完全取代push_back吗?

C++11中的emplace_back与push_back区别

vector的push_back和emplace_back两种方法的比较

vector 使用push_back 和emplace_back的区别