假设我有一个容器( vector )cont
和一个指向容器中某处的迭代器split
。
我想使用初始容器的内存获得两个子范围 [cont.begin()
, split) 和 [split, cont.end()
) -或者初始容器可能会缩小到第一个子范围,而剩余的内存将被第二个子范围窃取。
如果我正在使用手动分配的数组,我会得到类似的东西:
double *cont; // the 'container' - memory was allocated for this
int sz; // the size of the container
int cap; // the capacity of the container
然后(因为我手动进行簿记)我可以引入一个新的“容器”
double *slice = cont + split; // in this context split is an index and not an iterator
int slice_sz = sz - split;
int slice_cap = capacity - split;
那么“容器”将更新为
sz -= split;
cap = split;
这对 STL 可行吗?我可以使用现有的内存块并拥有两个具有更新成员的容器吗(大小,容量等......我想传递 .data
的黑客没有意义)
附言
我知道标准解决方案是使用迭代器范围,但我有一个需要使用完整容器的上下文,所以 [begin, split) 和 [split, end) 没有任何好处。
最佳答案
你不能有两个“容器”,但你可以有两个迭代器范围。
vector<double> v;
vector<double>::iterator split = v.begin() + offset;
do_something(v.begin(), split);
do_something(split, v.end());
那么问题就变成了,你想对你的两个范围执行什么样的操作?
关于c++ - 在不重新分配内存的情况下将 vector 拆分为 2 个子范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23611543/