Initializing a vector on a class constructor

I'm doing this A class which has a vector of B's. I'm initializing the vector on the constructor of the A class (I'm not sure if this is the right way, but it compiles). Besides this, I'm having a problem because I don't want that when initializing the vector that it initializes himself with the default construtor of B() because this makes me do a for loop to set the value that I want. It would be fine if the vector position stood NULL or stood 0 to size;

class B{
    int _t;
public:
    B(){ _t = 1; }
    B(int t) : _t(t){}
 };



class A{
    std::vector<B> _b;
public:
    A(int size): _b(size){
        for(int i = 0; i < size; i++){
        _b[i].setNumber(i);
    }
};  


int main() {
    int n = 3;
    A _a(n);
    return 0;
}

Upvotes: 2

Views: 1939

Answers (2)

shawn1874
shawn1874

Reputation: 1451

It does not compile. class B does not have a setNumber function. Initializing the vector to a size does not require you to do anything. It would just default construct number of objects equal to the specified size. Vector has a reserve member function that allows you to allocate enough memory for some number of elements without actually constructing objects. Perhaps that is what you were seeking. Obviously leaving it empty until you are ready to perform some form of insertion is another option. Hopefully one or more of the posted answers will help.

class A{
    std::vector<B> _b;
public:
    A(int size){
        _b.reserve(size);
    }
};

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227608

You can simply let the vector be default constructed (empty), then emplace_back into it:

A(int size) {
   _b.reserve(size);
   for(int i = 0; i < size; i++){
     _b.emplace_back(i);
   }
}

If you are stuck with a pre-C++11 compiler, you can push_back B objects into it:

A(int size) {
   _b.reserve(size);
   for(int i = 0; i < size; i++){
     _b.push_back(B(i));
   }
}

The calls to std::vector::reserve are to avoid re-allocations as the vector grows in size.

Upvotes: 5

Related Questions