您能否提供一种有效的方法来将std::vector
从n1
收缩到n2
(n2<=n1
)项,而不需要t
具有默认构造函数(即,resize()
不是一个选项,因为它需要默认构造函数,因为它也可以用于增长),并且只使用移动语义(不需要t
中的复制构造函数/赋值运算符)? 操作是否实际收缩分配的内存是可选的(我还没有决定哪一个更适合我的程序)。
到目前为止我所尝试的:
template<typename T> void Filter(vector<T> &v) {
// ... Filter the N1 items of the vector and move them to the first N2 positions
vector<T>(move(v)).swap(v); // this is wrong
}
如果需要就地执行,也许只需erase
就足够了:
v.erase(v.begin() + N2, v.end());
最简单的解决方案是擦除元素:
v.erase(v.begin() + N2, v.end());
如果需要,您可以减小保留的大小:
v.shrink_to_fit();
您还可以使用std::move
的其他重载来创建包含元素子集的新向量:
std::vector<T> filtered;
filtered.reserve(N2);
std::move(v.begin(), v.begin() + N2,
std::back_insert_iterator(filtered));
return filtered;
像这样的东西呢?
void foo(std::vector<T>& vec)
{
const std::size_t n = /* ... */;
std::vector<T>(
std::make_move_iterator(std::begin(vec)),
std::make_move_iterator(std::begin(vec) + n).swap(vec);
}