c++ - 仅修复 vector<vector<int>> 中的外部 vector

标签 c++

我想创建一个vector<vector<int>>其中外部 vector 是固定的(始终包含相同的 vector ),但内部 vector 可以更改。例如:

int n = 2; //decided at runtime
assert(n>0);
vector<vector<int>> outer(n); //outer vector contains n empty vectors

outer.push_back(vector<int>()); //modifying outer vector - this should be error

auto outer_it = outer.begin();
(*outer_it).push_back(3); //modifying inner vector. should work (which it does).

我尝试简单地做const vector<vector<int>> ,但这甚至使得内部 vector const .

这是我创建自己的自定义的唯一选择FixedVectors类,或者有更好的方法来做到这一点吗?

最佳答案

作者:definition ,

Vectors are sequence containers representing arrays that can change in size. Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

如果您不希望有一个大小变化的数据结构, vector 可能不是外层的最佳选择,使用 vector 数组怎么样。这样,数组的大小是固定的,无法修改,同时仍然可以自由地在运行时声明其大小。

vector<int> *outer;
int VectSize;
cout >> "size of vector array?"
cin >> VectSize;
outer = new vector<int>[VectSize]; //array created with fixed size
outer.push_back() //not happening

关于c++ - 仅修复 vector<vector<int>> 中的外部 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13776751/

相关文章:

C++ 在枚举中使用 ASCII 而不是字母

c++ - 组合返回 future 的功能

c++ - 函数参数和默认参数的评估顺序

c++ - 当有指向其中其他对象的指针时创建对象数组

c++ - 为 Beaglebone Black 编译 Qt

c++ - 游戏引擎设计问题

c++ - 如何像 "top"linux 命令一样进行控制台输入?

c++ - 如何将数据从一个结构链接到另一个结构

c++ - 如何计算FOP总数和特殊运算的浮点性能(exp sin sqrt)?

c++ - 对元素范围为 0 到 9999 的数组进行排序