提问者:小点点

在不触发默认构造函数且仅使用移动语义的情况下,将向量从N1项缩小到N2项


您能否提供一种有效的方法来将std::vectorn1收缩到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
}

共3个答案

匿名用户

如果需要就地执行,也许只需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);
}