标签:value 没有 type lease 参数 拷贝 push 作用 iostream
函数原型为:
void push_back(const value_type& val); void push_back(value_type& val);
作用:在vector当前最后一个元素之后添加一个新元素,会调用拷贝函数或者移动构造函数。
// vector::push_back #include <iostream> #include <vector> int main () { std::vector<int> myvector; int myint; std::cout << "Please enter some integers (enter 0 to end):\n"; do { std::cin >> myint; myvector.push_back (myint); } while (myint); std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n"; return 0; }
函数原型为:
template <class... Args> void emplace_back (Args&&... args);
作用:在vector当前最后一个元素之后添加一个新元素。这个新元素是使用args作为其构造函数的参数来构造的。
#include <vector> #include <string> #include <iostream> struct President { std::string name; std::string country; int year; President(std::string p_name, std::string p_country, int p_year) : name(std::move(p_name)), country(std::move(p_country)), year(p_year) { std::cout << "I am being constructed.\n"; } President(const President& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "I am being copy constructed.\n"; } President(President&& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "I am being moved.\n"; } President& operator=(const President& other); }; int main() { std::vector<President> elections; std::cout << "emplace_back:\n"; elections.emplace_back("Nelson Mandela", "South Africa", 1994); //没有类的创建 std::vector<President> reElections; std::cout << "\npush_back:\n"; reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); std::cout << "\nContents:\n"; for (President const& president: elections) { std::cout << president.name << " was elected president of " << president.country << " in " << president.year << ".\n"; } for (President const& president: reElections) { std::cout << president.name << " was re-elected president of " << president.country << " in " << president.year << ".\n"; } }
vector emplace_back() 和 push_back() 的区别
标签:value 没有 type lease 参数 拷贝 push 作用 iostream
原文地址:https://www.cnblogs.com/morwing/p/13631567.html