为什么remove_copy_if返回一个空向量?

Mic*_*hal 3 c++ stl stl-algorithm

你可以在下面的代码中向我解释一下我做错了什么吗?我希望第二个向量中的值> = 80,但它是空的.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Tester
{
    public:
        int value;
        Tester(int foo)
        {
            value = foo;
        }
};

bool compare(Tester temp)
{
    if (temp.value < 80)
        return true;
    else
        return false;
}

int main()
{
    vector<Tester> vec1;
    vector<Tester> vec2;
    vec1.reserve(100);
    vec2.reserve(100);

    for(int foo=0; foo<100; ++foo)
        vec1.push_back(Tester(foo));

    remove_copy_if(vec1.begin(), vec1.end(), vec2.begin(), compare);

    cout<< "Size: " << vec2.size() << endl;

    cout<< "Elements"<<endl;
    for(int foo=0; foo < vec2.size(); ++foo)
        cout << vec2.at(foo).value << " ";
    cout<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Die*_*ühl 6

该函数std::remove_copy_if()将非匹配元素从一个序列复制到另一个序列.电话

remove_copy_if(vec1.begin(), vec1.end(), vec2.begin(), compare);
Run Code Online (Sandbox Code Playgroud)

假设有一个合适的序列,从vec2.begin()实际上并非如此:没有任何东西.如果没有任何记忆reserve()d,vec2你可能会崩溃.你想要的是一个迭代器,它根据需要扩展序列:

std::remove_copy_if(vec1.begin(), vec1.end(), std::back_inserter(vec2), compare);
Run Code Online (Sandbox Code Playgroud)

通过这种方式,调用reserve()不是必需的,而只是潜在的性能优化.