Ken Y-N
Ken Y-N

Reputation: 15009

Is which element is deleted defined by std::unique?

Based on the example code here I wrote this small example (ideone Link):

#include <iostream>
#include <algorithm>
#include <string>

int main() 
{
    std::string s = "foo123bar456wibble";
    auto end = std::unique(s.begin(), s.end(), [](char l, char r){
        return std::isdigit(l) && std::isdigit(r);
    });
    // What does s hold?
    std::cout << std::string(s.begin(), end) << '\n';
}

My output is:

foo1bar4wibble

Does the standard guarantee this behaviour, or would this also be acceptable?

foo2bar6wibble

The linked cppreference page says:

Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten.

But is that normative text or just a suggested implementation?

Furthermore, cplusplus.com says:

Removes all but the first element from every consecutive group of equivalent elements in the range [first,last).

But again is that normative?

Upvotes: 2

Views: 109

Answers (1)

user1084944
user1084944

Reputation:

25.3.9 [alg.unique]/1

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.

Upvotes: 6

Related Questions