Search code examples
c++c++11uniquestandardsstl-algorithm

Do I have the guarantee that std::unique will keep the first element?


Consider a sorted std::vector<std::pair<int, int>> based on comparison of the first element of pair.

Now assume that I apply:

std::unique(std::begin(v), 
            std::end(v), 
            [](const std::pair<int, int>& x, const std::pair<int, int>& y)
            {return x.first == y.first;});

Do I have the guarantee that std::unique will keep the first element of every equal ranges ?


Solution

  • Yes.

    Eliminates all but the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.

    From here.

    The BinaryPredicate you have given just means that any element with y equal to the previous element x will be removed.