C++ 中"emplace_back" 與 "push_back" 的區(qū)別
創(chuàng)新互聯(lián)專注于平武企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站開發(fā),商城建設(shè)。平武網(wǎng)站建設(shè)公司,為平武等地區(qū)提供建站服務(wù)。全流程按需定制,專業(yè)設(shè)計,全程項目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
emplace_back和push_back都是向容器內(nèi)添加數(shù)據(jù).
對于在容器中添加類的對象時, 相比于push_back,emplace_back可以避免額外類的復(fù)制和移動操作.
"emplace_back avoids the extra copy or move operation required when using push_back."
參見: http://en.cppreference.com/w/cpp/container/vector/emplace_back
注意下面代碼中的emplace_back和push_back的添加方式(VS2012下編譯通過):
#include#include #include 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(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 elections; std::cout << "emplace_back:\n"; elections.emplace_back("Nelson Mandela", "South Africa", 1994); //沒有類的創(chuàng)建 std::vector 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"; } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!