Reputation: 1107
I know that I can initialize a vector like this:
vector<int> v{1,3,4,6};
However, when I define a class which contains a vector, I cannot initialize it in the position that I declare it, like this:
class C {
public:
vector<int> v;
C();
};
Thus I need to initialize it in the construction function. The following code works, but is not clean:
C::C() {
v.resize(4);
v[0]=1;
v[1]=3;
v[2]=4;
v[3]=6;
}
How could I initialize it neatly and directly like vector<int> v{1,3,4,6};
rather than assign values one by one ?
Edit:
Maybe I have not make my situation clear. The value of {1,3,4 6} may not be predefined values, they would depend on some logic and conditions: if(condition_a) {v[0] = 0; v[1]=3; ...} else {v[0]=4;v[0]=8;...}
. Thus I have to deal with some other things to know how to initialize this vector, so I cannot use initialization list as suggested in some answers. Any advice please?
Upvotes: 3
Views: 24253
Reputation: 124
This should work :
#include <vector>
class C {
std::vector<int> v;
public :
C() {
if(...)
v = { 0, 1, 2, 3, 4 };
else
v = { 5, 6, 7, 8, 9, 10, 11, 12};
//and other statement
}
};
Upvotes: 3
Reputation:
You can use an initializer list for the constructor.
Pertaining to conditional initialization as per your edited question, just initialize the vector contents to 0 and then apply whatever condition(s) you require and initialize specific values accordingly:
class C
{
public:
vector<int> v;
C() : v{0,0,0,0}
{ if(v.size()==4) // your condition
v[0]=1;
}
};
Upvotes: 1
Reputation: 172994
You can initialize it in member initializer list like
class C{
public:
vector<int> v;
C() : v {1,3,4,6} {}
};
Or use default member initializer (since C++11) like
class C{
public:
vector<int> v {1,3,4,6};
C() {}
};
Upvotes: 5
Reputation: 12273
Following would work:
C::C()
: v{ 1, 3, 4, 6 }
{}
Note that in the code above you are passing the std::initializer_list
to the std::vector
's constructor.
Upvotes: 7