令v
为 vector 。我希望 w
是索引 from
和 to
之间的 v
的子集。我可以做
std::vector<T> w(v.begin() + from, v.begin() + to);
但是,我不打算在以后使用v
。因此,我不需要在 from
和 to
之间复制数据。我需要创建一个指向 v.begin() + from
并且长度为 to - from
的 vector 。 v
使用的剩余内存应该被释放。请注意,如果它是 v
被重新定义我没问题(如果我想的话,我可以在之后切换到 w
)。
这有可能吗?
最佳答案
这应该可以解决 vector 问题。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v{ 11, 22, 33, 44, 55, 66, 77, 88, 99 };
constexpr size_t from = 3;
constexpr size_t to = 7;
if(to < v.size() - 1)
v.erase(v.begin() + to, v.end());
if(from > 0)
v.erase(v.begin(), v.begin() + from - 1);
v.shrink_to_fit();
for(auto i : v)
cout << i << ' ';
cout << endl;
}
关于c++ - 构建一个 vector 作为另一个 vector 的子集而不复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53753821/