首页 > 其他 > 详细

set存储自定义类

时间:2021-06-12 01:00:05      阅读:23      评论:0      收藏:0      [点我收藏+]

 STL各种容器和算法的sort和find函数对重载运算符的调用情况:

1) 二叉树类型的容器的sort和find都会调用operator < 。

2)线性类型容器sort会调用operator <;线性容器使用std::find会调用operator ==。

需要非常注意重载<运算符,分类讨论要周全。不然重则会导致dump机问题,轻则会导致排序不对。

对于< 号的重载要满足严格弱序的要求。

严格弱排序——strict weak ordering
严格是说在判断的时候会用"<",而不是"<=",弱排序是因为,一旦"<"成立便认为存在"<"关系,返回ture,而忽略了"="关系和">"区别,把它们归结为false。

满足严格弱序的3个条件:

    1.两个关键字不能同时严格弱序于对方。

    2.如果a严格弱序于b,且b严格弱序于c,则a必须严格弱序于c。

    3.如果存在两个关键字,任何一个都不严格弱序于另一个,则这两个关键字是相等的。

 

/*
 * setSelfDe.cpp
 *
 *  Created on: 2021年6月11日
 *      Author: 
 */

#include <iostream>
#include <set>
using namespace std;
class Bar {
public:
    int m_i;
    Bar(int x):m_i(x){}
    friend bool operator <(const Bar& lhs, const Bar& rhs)
    {
        return lhs.m_i < rhs.m_i;
    }
private:
};
int main()
{
    set<Bar> sbr;
    Bar b(3);
    Bar b1(3);
    Bar b2(4);
    sbr.insert(b);
    sbr.insert(b1);
    sbr.insert(b2);
    set<Bar>::iterator iter = sbr.find(b);
    if(iter != sbr.end())
    {
        cout << iter->m_i << endl;
    }
    else
    {
        cout << "not found" << endl;
    }
    set<Bar>::iterator iter1 = sbr.find(b1);
    if(iter1 != sbr.end())
    {
        cout << iter1->m_i << endl;
    }
    else
    {
        cout << "not found" << endl;
    }
    cout << "sbr size:" << sbr.size() << endl;
    return 0;
}

 

set存储自定义类

原文:https://www.cnblogs.com/guxuanqing/p/14875642.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!