Std :: unique example without equivalence relation (remove consecutive spaces)

The cppreference shows an example use std::uniqueto remove consecutive spaces from a string:

std::string s = "wanna go    to      space?";
auto end = std::unique(s.begin(), s.end(), [](char l, char r){
    return std::isspace(l) && std::isspace(r) && l == r;
});
// s now holds "wanna go to space?xxxxxxxx", where 'x' is indeterminate
std::cout << std::string(s.begin(), end) << '\n';

However, in the requirements section for a unique state

Elements are compared using the given binary predicate p. The behavior is undefined unless it is an equivalence relation.

So my question is: is this example valid? The predicate is clearly not reflective (the two characters "n" are compared unevenly) and, therefore, are not an equivalence relation.

+6
source share
2 answers

Equivalence_relation, :

a ~ a

, , , 'n' 'n'. , ( ).

:

[](const char& l, const char& r)
{
    return (&l == &r)
        || (l == r && std::is_space(l));
}

, , UB , .

, - ( UB).

+2

unique: " , , "

, . . 'n' , false.

0

All Articles