C++11 emplace_back on vector?

前端 未结 8 608
借酒劲吻你
借酒劲吻你 2020-12-02 14:58

Consider the following program:

#include 
#include 

using namespace std;

struct T
{
    int a;
    double b;
    string c;
};

         


        
8条回答
  •  遥遥无期
    2020-12-02 15:32

    You can use the {} syntax to initialize the new element:

    V.emplace_back(T{42, 3.14, "foo"});
    

    This may or may not be optimized, but it should be.

    You have to define a constructor for this to work, note that with your code you can't even do:

    T a(42, 3.14, "foo");
    

    But this is what you need to have emplace work.

    so just:

    struct T { 
      ...
      T(int a_, double b_, string c_) a(a_), b(b_), c(c_) {}
    }
    

    will make it work the desired way.

提交回复
热议问题