• 呜呜呜


    #include <iostream>
    #include <set>
    using namespace std;

    /*定义一个Student结构体,包括name和age等数据,
    要求编程实现在set中查找一个name == "张三", age == 13的操作。*/
    /*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;
    }

  • 相关阅读:
    hdu 4258 Covered Walkway
    hdu 2337 Escape from Enemy Territory
    二分查找
    hdu 2335 Containers
    最大流 Dinic
    进程和并发编程
    黏包
    socket
    网络编程
    异常处理
  • 原文地址:https://www.cnblogs.com/cs-lcy/p/7224724.html
Copyright © 2020-2023  润新知