码迷,mamicode.com
首页 > 其他好文 > 详细

vector emplace_back() 和 push_back() 的区别

时间:2020-09-17 18:10:49      阅读:31      评论:0      收藏:0      [点我收藏+]

标签:value   没有   type   lease   参数   拷贝   push   作用   iostream   

push_back:

函数原型为:

void push_back(const value_type& val);
void push_back(value_type& val);

作用:在vector当前最后一个元素之后添加一个新元素,会调用拷贝函数或者移动构造函数。

// vector::push_back
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  int myint;

  std::cout << "Please enter some integers (enter 0 to end):\n";

  do {
    std::cin >> myint;
    myvector.push_back (myint);
  } while (myint);

  std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";

  return 0;
}

emplace_back:

函数原型为:

template <class... Args>
void emplace_back (Args&&... args);

作用:在vector当前最后一个元素之后添加一个新元素。这个新元素是使用args作为其构造函数的参数来构造的。

和push_back类似,但是push_back会将现有对象拷贝或移动到新的容器,emplace_back是直接构造新的对象。
#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(const President& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    {
        std::cout << "I am being copy 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";  
    }
}

 

vector emplace_back() 和 push_back() 的区别

标签:value   没有   type   lease   参数   拷贝   push   作用   iostream   

原文地址:https://www.cnblogs.com/morwing/p/13631567.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!