【问题标题】:Why remove_copy_if returns an empty vector?为什么 remove_copy_if 返回一个空向量?
【发布时间】:2012-08-20 23:45:28
【问题描述】:

您能否向我解释一下我在以下代码中做错了什么? 我希望第二个向量中的值 >= 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;
}

【问题讨论】:

    标签: c++ stl stl-algorithm


    【解决方案1】:

    函数std::remove_copy_if() 将不匹配的元素从一个序列复制到另一个序列。来电

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

    假设从vec2.begin() 开始有一个合适的序列,但实际上并非如此:什么都没有。如果reserve()d 对于vec2 没有任何内存,您可能会崩溃。你想要的是一个迭代器,它可以根据需要扩展序列:

    std::remove_copy_if(vec1.begin(), vec1.end(), std::back_inserter(vec2), compare);
    

    这样就不需要调用reserve(),而只是潜在的性能优化。

    【讨论】:

      【解决方案2】:

      标准算法适用于迭代器,对迭代器所属的容器一无所知。您将vec2.begin() 作为输出迭代器参数传递给remove_copy_if,它会盲目地递增它,不知道vec2 是空的,耗尽分配的空间。您需要在调用之前传递back_insert_iterator 或将向量调整为合适的大小。

      【讨论】:

        猜你喜欢
        • 2021-07-20
        • 1970-01-01
        • 2019-04-15
        • 1970-01-01
        • 2012-05-23
        • 2013-11-30
        • 1970-01-01
        • 2022-12-03
        • 2018-04-05
        相关资源
        最近更新 更多