Why doesn't this vector assignment work?

2019-07-25 16:47发布

问题:

Similar Questions:

  • STL vector reserve() and copy()
  • std::vector reserve() and push_back() is faster than resize() and array index, why?
  • std::vector::resize() vs. std::vector::reserve()

#include <vector>
#include <iostream>

using namespace std;

int main() {
  vector<vector<int> > vvi;
  vvi.resize(1);
  vvi[0].reserve(1);
  vvi[0][0] = 1;

  vector<int> vi = vvi[0];

  cout << vi[0]; // cout << vvi[0][0]; works

  return 0;
}

This gives me a seg fault, and I can't tell why.

回答1:

 vvi[0].reserve(1);
 vvi[0][0] = 1;

You need resize, not reserve.

Accessng an element i where i>=v.size() is undefined behavior. reserve affects capacity, not size.

If I were to go into the practical aspect, I might speculate that perhaps you might get away with the assignment vvi[0][0] = 1; (in Release Mode, at least). But the main practical problem lies here

vector<int> vi = vvi[0];

The problem is that vvi[0]'s size is 0, so vi's internal array size is 0, regardless of vvi[0]'s capacity. That's I think where you get the seg fault, after you

cout << vi[0]; // cout << vvi[0][0]; works

But that's all speculations. The correct answer to your question is that this

vvi[0].reserve(1);
vvi[0][0] = 1;

already has undefined behavior, and no further considerations are required.