1

Why can't I add an item to vector :

std::vector < std::vector <std::string> > my_list;
my_list[0][0] = "this is text";

std::cout << "text: " << my_list[0][0] << std::endl;

What am I doing wrong?

UKMonkey
  • 6,941
  • 3
  • 21
  • 30
GUIMish
  • 23
  • 6
  • 2
    When you create a vector it is empty. ***All*** indexing into it will be out of bounds. Perhaps you should [get a good beginners book or two](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? – Some programmer dude Dec 07 '17 at 11:54
  • You need to init all the vectors inside the vector of vectors. – JLev Dec 07 '17 at 11:54

1 Answers1

0

Unlike some containers (such as std::map), a std::vector does not grow on demand.

So before you index an element you need to make sure the std::vector has the appropriate size. You can do that by passing a size on construction.

In your case you could use the flashy syntax

std::vector < std::vector <std::string> > my_list{{"this is a test"}};

to get things going.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483