Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Initialize vector with another vector

Consider the class Foo and Bar:

class Foo
{
public:
    Foo() = default;
    Foo(int);
};

class Bar
{
public:
    Bar() = default;
    Bar(const std::vector<int> & v);

private:
    std::vector<Foo> data_;
};

How to write the constructor Bar(const std::vector<int> & v) so that each element of v can initialize a Foo object with Foo(int)?

like image 710
stone-zeng Avatar asked May 15 '18 17:05

stone-zeng


1 Answers

You can use:

Bar(const std::vector<int> & v) : data_(v.begin(), v.end()) {}
like image 76
R Sahu Avatar answered Oct 16 '22 19:10

R Sahu