Reputation: 8497
I have a class
class A
{
private:
std::vector< std::vector<int> > v;
//other statements
}
I would like to initialize both dimensions of this vector by passing them to the constructor of the class, possibly using initializer lists.
This question asks about the same question for a vector of integers, and this asks about initialization of a vector of vectors, but outside any class. I want to initialize the sizes of both dimensions, but the vector is a class member.
How can I do this?
Upvotes: 2
Views: 2971
Reputation: 69854
Did you want to initialise with existing data?
struct Matrix
{
Matrix(std::initializer_list< std::initializer_list<int> > ilil)
{
data_.reserve(ilil.size());
for (auto&& il : ilil)
{
data_.emplace_back(il);
}
}
std::vector< std::vector<int> > data_;
};
void test()
{
auto m = Matrix {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
}
Upvotes: 2
Reputation: 10591
you can put them in the member initializer lists
like this
class A{
public:
A(int dim1,int dim2):v(dim1,std::vector<int>(dim2)){}
private:
std::vector< std::vector<int> > v;
};
or you can use vector::resize
class A{
public:
A(int dim1,int dim2){v.resize(dim1,std::vector<int>(dim2));}
private:
std::vector< std::vector<int> > v;
};
Upvotes: 5