我想创建一个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/