Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using push_back on a vector<vector<string> > [closed]

Tags:

c++

stl

I'm somewhat embarrassed that such a simple problem has stymied me, but after a few hours of fruitless googling, I'm still stuck.

To simplify my problem, the 2nd line of this crashes:

  vector<vector<string> > sorted_words;
  sorted_words[0].push_back("hello");

Shouldn't sorted_words[0] represent an empty vector that I can legally push_back onto?

like image 378
They Call Me Bruce Avatar asked Apr 28 '13 01:04

They Call Me Bruce


1 Answers

No. You have a vector of vectors. You haven't added anything to either vector by line 2, so sorted_words[0], the first element in sorted_words, doesn't exist yet.

You're trying to push "hello" into a null vector.

Null pointer dereference!

I would ask "do you really want a vector of vectors, or just a vector of strings"?

If you want a vector of strings, then use:

vector<string> sorted_words;
sorted_words.push_back("hello");

If you really do want a vector of vectors (of strings), then use:

vector<string> first_vector;
first_vector.push_back("hello");
sorted_words.push_back(first_vector);
like image 141
Nate Avatar answered Oct 14 '22 06:10

Nate