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

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

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

2020-01-26 14:12:09
字體:
來源:轉載
供稿:網友

 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";   } } 

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 百色市| 栖霞市| 新郑市| 郴州市| 安义县| 大关县| 黑山县| 清水河县| 辉南县| 黄山市| 大田县| 固镇县| 观塘区| 马山县| 崇明县| 西乌珠穆沁旗| 盐山县| 寿宁县| 谢通门县| 老河口市| 清原| 山阴县| 泸溪县| 马边| 师宗县| 岳池县| 合阳县| 资源县| 茌平县| 玉山县| 濉溪县| 峨山| 偃师市| 肃北| 偃师市| 垫江县| 清水县| 保德县| 岫岩| 临猗县| 峨山|