当比较对象始终返回 true 或 false 时,标准容器的预期行为

Din*_*rya 1 c++ c++11 c++17

当自定义比较对象始终返回相同的结果(可能是真或假但始终相同),同时将元素放在标准库容器中时,例如std::setstd::map. 例如

struct A{
   int i_mem;
   double d_mem;
};

bool operator > (const A& first, const A& second)
{
    //This is hard coded just for the sake of example and actual code could still return always return the same value due to bug in the logic.

    return false;
}
Run Code Online (Sandbox Code Playgroud)

然后创建对象,如

set<A, greater<A>> mset{{5,434.5},{1,32.4},{3,29.3}};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,(5,434.5)当使用 g++-10 测试时,该集合只有第一个元素。

Ala*_*les 6

如果比较器始终返回 false,则a < b || b < a始终false如此std::set将所有元素视为相等并且只包含一个元素。

如果比较器总是返回真,那么a < b && b < a总是true没有意义并且违反严格的弱排序,导致未定义的行为。