Home I can't add item to ( std::vector < std::vector <std::string> > )
Reply: 1

I can't add item to ( std::vector < std::vector <std::string> > )

GUIMish Published in 2017-12-07 11:53:14Z

This question already has an answer here:

  • add an element to an empty vector in c++: why push.back works and [] not 1 answer
  • Loading data into a vector of structures 2 answers

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?

Bathsheba Reply to 2017-12-07 11:56:12Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.316672 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO