c++ - 在不重新分配内存的情况下将 vector 拆分为 2 个子范围

标签 c++ stl

假设我有一个容器( 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/

相关文章:

c++ - 如何写union类型的推导指南

c++ - lua用户数据按值传递

c++ - 将 int 数组的内容写入 vector

c++ - 多集上的 std::transform 给我错误 C3892

c++ - 初始化在构造函数中实现自身的类模板

c++ - 弹性和 Bison : string literal

c++ - 使用基类指针访问派生类成员

c++ - doxygen生成错误

c++ - 在 C++ 中从 vector<int> 生成子列表

c++ - C++ 中的 tr1::array 删除所有元素