• set


    当set存的是一个结构体时,若想用 find 函数,应在结构体内部写一个函数

    struct node
    {
        int x;
        int num;
        
        bool operator< (const node &v)const{ // 先比较 x , 若 x 相同再比较num,小的返回true
            if (x < v.x) return true;
            else if (x == v.x) {
                if (num < v.num) return true;
                else return false;
            }
            else return false;
        }
    };
    set<node>s, f;
    
    #include <iostream>   
    #include <set>   
    using namespace std;  
       
    /*Student结构体*/  
    struct Student {  
        string name;  
        int age;  
        string sex;  
    };  
       
    /*“仿函数"。为Student set指定排序准则*/  
    class studentSortCriterion {  
        public:  
            bool operator() (const Student &a, const Student &b) const {  
                /*先比较名字;若名字相同,则比较年龄。小的返回true*/  
                if(a.name < b.name)  
                    return true;  
                else if(a.name == b.name) {  
                    if(a.age < b.age)  
                        return true;  
                    else  
                        return false;  
                } else  
                    return false;  
            }  
    };  
       
    int main()  
    {  
        set<Student, studentSortCriterion> stuSet;  
       
        Student stu1, stu2;  
        stu1.name = "张三";  
        stu1.age = 13;  
        stu1.sex = "male";  
       
        stu2.name = "李四";  
        stu2.age = 23;  
        stu2.sex = "female";  
       
        stuSet.insert(stu1);  
        stuSet.insert(stu2);  
       
        /*构造一个测试的Student,可以看到,即使stuTemp与stu1实际上并不是同一个对象, 
         *但当在set中查找时,仍会查找成功。这是因为已定义的studentSortCriterion的缘故。 
         */  
        Student stuTemp;  
        stuTemp.name = "张三";  
        stuTemp.age = 13;  
       
        set<Student, studentSortCriterion>::iterator iter;  
        iter = stuSet.find(stuTemp);  
        if(iter != stuSet.end()) {  
            cout << (*iter).name << endl;  
        } else {  
            cout << "Cannot fine the student!" << endl;  
        }  
       
        return 0;  
    }
    
    东北日出西边雨 道是无情却有情
  • 相关阅读:
    第二章 信息的表示和处理(下)
    第二章 信息的表示和处理
    IDEA中新建子模块
    手动实现一个可重入锁
    Lock接口的认识和使用
    JDK提供的原子类原理与使用
    深入理解volatile原理与使用
    模拟死锁
    模拟自旋锁
    grep 如何自动标注颜色
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/9630542.html
Copyright © 2020-2023  润新知