samedi 20 février 2021

Best way to copy a vector

I have a struct Y with a vector of type X, I would like to ask whether in this case assign is the best solution or copy would be better? Should I resize y.xVec?

#include <iostream>
#include <vector>

struct X {
  X(int x):x_(x)
  {}
  int x_;
};

struct Y {
  std::vector<X>xVec;
};

int main()
{
    X x1(1);
    X x2(2);
    std::vector<X> v = {x1,x2};
    
    Y y;
    y.xVec.assign(v.begin(), v.end());
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire