Effective STL 第21条

2022-09-29  本文已影响0人  懒生活

如果你自己指定容器的比较函数,那么切记不要出现等号
如果你定义如下的set<int, less_equal<int>> intSet; 这个intSet在下面的代码中执行到第二个intSet.insert(5);的时候,程序就会崩溃. 但是编译是能过的. 因为按set的等价原则, 第二个5 通过if ((5 not less_equal others) And (others not less_equal 5))来确定等价关系.当第二个5和set中已经插入的5比较的时候用的表达式是if(!(5>=5) && !(5>=5)) 这个表达式成立表示等价,不成立表示不等价, 所以这里会判定第二个5于已经插入set的第一个5不等价.这会导致第二个5被插入set. 从而破坏了set的不重复的特性. 运行期会崩溃.

void printStringVec(int a)
{
    cout << a << endl;
}

int main()
{
    set<int, less_equal<int>> intSet;
    intSet.insert(5);
    intSet.insert(10);
    intSet.insert(5);
    for_each(intSet.begin(), intSet.end(), printStringVec);
}

所以如果是自己写关联容器的比较函数的时候,不要出现"大于等于" 或者"小于等于"做判决. 类似下面的判决条件也不行,因为return !(*ps1 < *ps2); 等价于 return (*ps1 >= *ps2);

class StringPtrGreater
{
public:
    bool operator()(const string* ps1, const string* ps2) const
    {
        return !(*ps1 < *ps2);
    }
};
上一篇 下一篇

猜你喜欢

热点阅读