lundi 22 mars 2021

incorrect output using STL remove_if [duplicate]

I am trying to remove elements from a vector of ints using std::remove_if, but am not getting the required output.

Initial vector members: {0, 1, 2, 1, 3, 1, 4, 5, 1, 6, 1, 7, 1, 8, 1, 9}

Required Output: {0, 2, 3, 4, 5, 6, 7, 8, 9}

Actual Output: {0, 2, 3, 4, 5, 6, 7, 8, 9, 6, 1, 7, 1, 8, 1, 9}

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

    class Equal
    {
    public:
    Equal(int a): a_(a){}
    bool operator()(int b)
    {
    return a_ == b;
    }
    
    private:
    int a_;
    };
    
    int main()
    {
    std::vector<int> vi{0, 1, 2, 1, 3, 1, 4, 5, 1, 6, 1, 7, 1, 8, 1, 9};
    
    std::cout << std::endl;
    std::remove_if(vi.begin(), vi.end(), Equal(1));
    for (const auto &i : vi) std::cout << i << " ";
    return 0;
    }

Aucun commentaire:

Enregistrer un commentaire