Help ASAP with initializing vector in constructor

How do I initialize a vector in constructor? I am getting error "debug assertion failed...Expressed vector subscript out of range" :(

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  class Type{
      private:
         vector<Type*> name;
         ...
      public:
          Type();
          ...

//.cpp file
   Type::Type(){
      name.at(0)=NULL;
      name.at(1)=NULL;
      name.at(2)=NULL;
      name.at(3)=NULL;
     }
you have to initialize the vector before you can store anything in it.

Type::Type() : name(4){}

will initialize the vector to a size of 4 without assigning any values.

Also you access the elements of a vector with name[0], name[1]...
not name.at(0)
Last edited on
your vector is implicitly of size 0
push_back() statement is one of the options for adding new values

1
2
3
4
5
6
Type::Type()
{
    bla.push_back(nullptr);
    bla.push_back(nullptr);
    ...
}
Last edited on
Thanks rich1 you fixed the problem. Thanks redwayne as well..
Type::Type() : name(4, nullptr) {}

http://www.cplusplus.com/reference/vector/vector/vector/
constructor #2
Topic archived. No new replies allowed.