vector emplace_back() 和 push_back() 的區別
阿新 • • 發佈:2020-09-08
push_back:
函式原型為:
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; }
emplace_back:
函式原型為:
template <class... Args> voidemplace_back (Args&&... args);
作用:在vector當前最後一個元素之後新增一個新元素。這個新元素是使用args作為其建構函式的引數來構造的。
和push_back類似,但是push_back會將現有物件拷貝或移動到新的容器,emplace_back是直接構造新的物件。#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"; } }