Why doesn't this vector assignment work?

倾然丶 夕夏残阳落幕 提交于 2019-12-24 15:14:44

问题


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.



来源:https://stackoverflow.com/questions/15732196/why-doesnt-this-vector-assignment-work

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