vendredi 8 janvier 2021

Unexpected behavior using `std::count` on `std::vector` of pairs

My goal is to completely remove all elements in a std::vector<std::pair<int, int>> that occur more than once.

The idea was to utilize std::remove with std::count as part of the predicate. My approach looks something like this:

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

using std::cout;
using std::endl;
using i_pair = std::pair<int, int>;

int main()
{
    std::vector<i_pair> vec;
    vec.push_back(i_pair(0,0));
    vec.push_back(i_pair(0,1));
    vec.push_back(i_pair(1,1));
    vec.push_back(i_pair(0,1));

    auto predicate = [&](i_pair& p)
    {
        return std::count(vec.begin(), vec.end(), p) > 1;
    };
    auto it = std::remove_if(vec.begin(), vec.end(), predicate);

    cout << "Reordered vector:" << endl;
    for(auto& e : vec)
    {
        cout << e.first << " " << e.second << endl;;
    }
    cout << endl;
    
    cout << "Number of elements that would be erased: " << (vec.end() - it) << endl;

    return 0;
}

The array gets reordered with both of the (0,1) elements pushed to the end, however the iterator returned by std::remove points at the last element. This means that a subsequent erase operation would only get rid of one (0,1) element.

Why is this behavior occurring and how can I delete all elements that occur more than once?

Aucun commentaire:

Enregistrer un commentaire