C++ 中"emplace_back" 與 "push_back" 的區(qū)別
C++ 中"emplace_back" 與 "push_back" 的區(qū)別
emplace_back和push_back都是向容器內(nèi)添加數(shù)據(jù).
對(duì)于在容器中添加類(lèi)的對(duì)象時(shí), 相比于push_back,emplace_back可以避免額外類(lèi)的復(fù)制和移動(dòng)操作.
"emplace_back avoids the extra copy or move operation required when using push_back."
參見(jiàn): http://en.cppreference.com/w/cpp/container/vector/emplace_back
注意下面代碼中的emplace_back和push_back的添加方式(VS2012下編譯通過(guò)):
#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(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); //沒(méi)有類(lèi)的創(chuàng)建
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";
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
C++數(shù)據(jù)結(jié)構(gòu)與算法的基礎(chǔ)知識(shí)和經(jīng)典算法匯總
終是到了標(biāo)志著大二結(jié)束的期末考試了,對(duì)于《算法設(shè)計(jì)與分析》這門(mén)課,我需要總結(jié)一下學(xué)過(guò)的所有算法的思想以及老師補(bǔ)充的關(guān)于兩個(gè)復(fù)雜度和遞歸的概念思想,以及更深層次的理解,比如用畫(huà)圖的方式表達(dá)出來(lái),我覺(jué)得可以用博客記錄總結(jié)一下,分享給大家,希望能有所幫助2022-05-05
C++解決業(yè)務(wù)辦理時(shí)間問(wèn)題示例解析
這篇文章主要為大家介紹了C++解決業(yè)務(wù)辦理時(shí)間問(wèn)題示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
C語(yǔ)言調(diào)試手段:鎖定錯(cuò)誤的實(shí)現(xiàn)方法
本篇文章是對(duì)在C語(yǔ)言調(diào)試中,鎖定錯(cuò)誤的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C++面向?qū)ο笳Z(yǔ)言自制多級(jí)菜單功能實(shí)現(xiàn)代碼
菜單類(lèi)主要負(fù)責(zé)菜單的創(chuàng)建、修改、刪除,是包含菜單結(jié)構(gòu)組織和響應(yīng)函數(shù)的模型,用戶(hù)擁有充分的自主性,可根據(jù)需要自定義菜單顯示和響應(yīng)函數(shù),這篇文章主要介紹了C++面向?qū)ο笳Z(yǔ)言自制多級(jí)菜單,需要的朋友可以參考下2024-06-06
淺析string類(lèi)字符串和C風(fēng)格字符串之間的區(qū)別
string類(lèi)是標(biāo)準(zhǔn)庫(kù)的類(lèi),并不是內(nèi)置類(lèi)型,標(biāo)準(zhǔn)庫(kù)就像是我們自己定義的類(lèi)差不多的,string類(lèi)型對(duì)象沒(méi)有標(biāo)配'\0'結(jié)尾的2013-09-09
C語(yǔ)言編程中生成隨機(jī)數(shù)的入門(mén)教程
這篇文章主要介紹了C語(yǔ)言編程中生成隨機(jī)數(shù)的入門(mén)教程,包括利用rand()函數(shù)來(lái)編寫(xiě)隨機(jī)數(shù)生成器的示例,要的朋友可以參考下2015-12-12

