std::unique 没有等价关系的例子(去掉连续的空格)

std::unique example with no equivalence relationship (remove consecutive spaces)

cppreference 上有一个关于如何使用 std::unique 从字符串中删除连续空格的示例:

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';

但是,在唯一要求部分中指出

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

所以我的问题是:给定的例子有效吗? 谓词显然不是自反的(两个 'n' 字符比较不相等)因此不是等价关系。

谓词确实不尊重Equivalence_relation,尤其是自反性:

a ~ a

您指出的示例可能有效,但第一个 'n' 可能与第二个 'n' 不同。 问题在于自我比较是错误的(space 字符除外)。

修复谓词的一种方法是考虑地址:

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

事实是,与自身比较对于该算法几乎没有用,因此此处的 UB 符合作者在大多数实现中所期望的。

有效的实现可能会检查谓词的自反性,如果错误则执行任何操作(如 UB)。

唯一:"Eliminates all but the first element from every consecutive group of equivalent elements from the range"

如果您将示例谓词的元素定义为仅 space,那么一切都是正确的。等价应仅应用于 spaces。 'n' 不是 space 所以谓词 returns 为假。