zoukankan      html  css  js  c++  java
  • set存储自定义类

     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;
    }
  • 相关阅读:
    AcWing 3302. 表达式求值
    AcWing 828. 模拟栈
    六种风格时间显示
    web2.0常用配色.
    CSS浏览器兼容问题详解
    jQuery Cycle Plugin Beginner Demos
    jQuery插件Clipboard Copy(复制)。
    精通jQuery选择器使用
    jQuery插件右下角弹出信息
    CSS关于box(盒模式)的一系列问题
  • 原文地址:https://www.cnblogs.com/guxuanqing/p/14875642.html
Copyright © 2011-2022 走看看