## CSDN博客

### Effective STL： Item 21：永远让比较函数对相同元素返回false

Item 21：永远让比较函数对相同元素返回false

set<int, less_equal<int> > s;               // s is sorted by <=

s.insert(10);                               // insert the value 10

s.insert(10);

set遍历它的内部数据结构以查找加入10B的位置。 最终，它总要检查10B是否与10A相同。 关联容器对“相同”的定义是equivalence(见Item 19)（WQ注： equivalence应指“数学相等”，two elements are equal if neither is less than the other，见《The C++ Standard Library》中文版P82，英文版电子P77；equality指“逻辑等价”，使用operator==()，见《The Standard Template Library》英文电子版P30)因此set测试10B是否数学等值于10A。 当执行这个测试时，它自然是使用set的比较函数。在这一例子里，是operator<=，因为我们指定set的比较函数为less_equal，而less_equal就是operator<=。于是，set将计算这个表达式是否为真：

!(10 A <= 10 B ) && !(10 B <= 10 A )       // test 10 A and 10 B for equivalence

!(true) && !(true)

false && false

struct StringPtrGreater:                             // highlights show how

public binary_function<const string*,            // this code was changed

const string*,            // from page 89. Beware,

bool> {                   // this code is flawed!

bool operator()(const string *ps1, const string *ps2) const

{

return !( *ps1 < *ps2);                      // just negate the old test;

}                                                // this is incorrect!

};

struct StringPtrGreater:                             // this is a valid

public binary_function<const string*,            // comparison type for

const string*,            // associative containers

bool> {

bool operator()(const string *ps1, const string *ps2) const

{

return *ps2 < *ps1;                          // return whether *ps2

}                                                // precedes *ps1 (i.e., swap

// the order of the

};                                                   // operands)

multiset<int, less_equal<int> > s;             // s is still sorted by <=

s.insert(10);                                  // insert 10 A

s.insert(10);                                  // insert 10 B

0 0