Vincent
Vincent

Reputation: 60381

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 ?

Upvotes: 5

Views: 370

Answers (2)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

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.

Upvotes: 9

Eponymous
Eponymous

Reputation: 6821

Yes. The C++14 draft standard says in section 25.3.9 [alg.Unique] (emphasis mine):

Effects: For a nonempty range, eliminates all but the first element from every consecutive group of equivalent elements referred to by the iterator i in the range [first + 1,last) for which the following conditions hold: *(i - 1) == i or pred((i - 1), *i) != false.

The citation of the standard is important here because the usual Internet sources on this point give two different answers: en.cppreference.com does not give the guarantee, but cplusplus.com (cited by Ben above has the guarantee.)

Upvotes: 2

Related Questions