国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++ 中"emplace_back" 與 "push_back" 的區別

2020-05-23 13:50:26
字體:
來源:轉載
供稿:網友

 C++ 中"emplace_back" 與 "push_back" 的區別

emplace_backpush_back都是向容器內添加數據.

對于在容器中添加類的對象時, 相比于push_back,emplace_back可以避免額外類的復制和移動操作.

"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 <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); //沒有類的創建    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";   } } 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 景东| 突泉县| 株洲市| 明光市| 武定县| 东台市| 富民县| 宁强县| 渝中区| 永泰县| 汾阳市| 大渡口区| 西充县| 岢岚县| 湖南省| 策勒县| 轮台县| 平原县| 额敏县| 缙云县| 康平县| 万州区| 龙里县| 黄石市| 土默特右旗| 廊坊市| 环江| 唐海县| 贡嘎县| 凤冈县| 建阳市| 昭苏县| 柏乡县| 界首市| 昌都县| 房山区| 合水县| 威宁| 西乌珠穆沁旗| 遂川县| 昌都县|