3

我有一个带有一些值的向量。我怎样才能将它复制到另一个向量,所以除了一个特定的值(位于位置x-x当然将是一个参数)之外的所有值都将被复制?

此外,我想将 location 中的值x用于其他用途,因此我更希望将其保存。

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

4

3 回答 3

3

除了一个特定值之外,如何复制 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相应地使用和调整谓词的逻辑。

于 2013-11-06T09:09:23.110 回答
1

正如 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;
于 2013-11-06T09:16:34.263 回答
1

std::copy_if如果你有 c++11,则使用,否则:

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具有随机访问迭代器。

于 2013-11-06T09:18:51.830 回答