如何复制除一个特定元素之外的向量

How to copy a vector except one specific element?

本文关键字:元素 向量 何复制 复制 一个      更新时间:2023-10-16

我有一个带有一些值的向量。如何将其复制到另一个向量,以便复制除特定值(位于位置 x - 当然x将是一个参数)之外的所有值?

此外,我想将位置x的值用于其他用途,因此我希望它将被保存。

有没有简单的方法可以做到这一点?

如何复制除一个特定值之外的 stl 向量?

您可以使用std::copy_if

std::vector<T> v = ....;
std::vector<T> out;
T x = someValue;
std::copy_if(v.begin(), v.end(), std::back_inserter(out), 
             [x](const T& t) { return t != x; });

如果没有 C++11 支持,则可以使用 std::remove_copy_if 并相应地调整谓词的逻辑。

如果您有 C++11,请使用 std::copy_if,否则:

void foo(int n) {
    std::vector<int> in;
    std::vector<int> out;
    std::copy(in.begin(), in.begin() + n, out.end());
    std::copy(in.begin() + n + 1, in.end(), out.end());
}

这是有效的std::vector因为它具有随机访问迭代器。

正如Luchian建议的那样,你应该使用erase()

#include <vector>
#include <iostream>
#include<algorithm>
int main(){
    std::vector<int> vec1;
    vec1.push_back(3);
    vec1.push_back(4); // X in your question
    vec1.push_back(5);
    std::vector<int> new_vec;
    new_vec = vec1;
    new_vec.erase(std::find(new_vec.begin(),new_vec.end(),4));
    for (unsigned int i(0); i < new_vec.size(); ++i)
        std::cout << new_vec[i] << std::endl;
    return 0;
}

对于您的第二个问题,确定向量中元素的索引

 // determine the index of 4 ( in your case X)
 std::vector<int>::iterator it;
 it = find(vec1.begin(), vec1.end(), 4);
 std::cout << "position of 4: " << distance(vec1.begin(),it) << std::endl;