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?
Aucun commentaire:
Enregistrer un commentaire