为什么矢量分配不起作用

为什么矢量分配不起作用

本文介绍了为什么矢量分配不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似问题:

  • 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.

推荐答案

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

您需要resize,而不是reserve.

访问元素i,其中i>=v.size()是未定义的行为. reserve影响capacity,而不影响size.

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

如果我要进行实际操作,我可能会推测也许您可能会放弃vvi[0][0] = 1;作业(至少在发布模式"下).但是主要的实际问题就在这里

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

问题在于vvi[0]的大小为0,所以vi的内部数组大小为0,而与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.

这篇关于为什么矢量分配不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:37