雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

C++ 中"emplace_back" 與 "push_back&

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點(diǎn)擊:

 C++ 中"emplace_back" 與 "push_back" 的區(qū)別

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

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

上一篇:C語言中的參數(shù)傳遞機(jī)制詳解

欄    目:C語言

下一篇:C++ 中實(shí)現(xiàn)把EXCEL的數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫(ACCESS、MSSQL等)實(shí)例代碼

本文標(biāo)題:C++ 中&quot;emplace_back&quot; 與 &quot;push_back&

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/1659.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有