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

﹥>﹥吖頭↗ 提交于 2020-01-02 05:03:55

问题


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?


回答1:


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);



回答2:


Your object sorted_words is a vector of vectors.

vector<vector<string>> sorted_words;
if (sorted_words.empty()) {
  sorted_words.resize(1);
}
sorted_words[0].emplace_back("Hello");

In general, accession through operator to a vector has the implicit precondition that the vector has a size greater than i.




回答3:


Your sorted_words has not been allocated memory. so sorted_words[0] will try to access something that does not exist yet.

try the following:

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

Or you can do the following:

 vector<vector<string> > sorted_words;
 vector<string> innerVec;
 innerVec.push_back("Hello");
 innerVec.push_back("World");
 sorted_words.push_back(innerVec);

You can view a live example here: http://ideone.com/KlliR8#view_edit_box



来源:https://stackoverflow.com/questions/16258711/using-push-back-on-a-vectorvectorstring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!