zoukankan      html  css  js  c++  java
  • c++ set容器排序准则

    转载两篇博客:

    http://blog.csdn.net/lishuhuakai/article/details/51404214

    http://blog.csdn.net/lihao21/article/details/6302196/

    以下是实验代码:

    #include <iostream>  
    #include <set>  
    #include<algorithm>
    using namespace std;  
          
        /*Student结构体*/   
        struct Student {  
        string name;  
        int id;  
        int score;  
        };  
          
            /*“仿函数"。为Student set指定排序准则*/  
            class studentSortCriterion {  
            public:  
           /*类型要与set容器类型一致*/
    bool operator() (const Student *a, const Student *b) const { return (a->id == b->id) ? (a->score > b->score) :(a->id > b->id); } }; int main() { set<Student*, studentSortCriterion> stuSet; set<Student*> stus; Student stu1, stu2,stu3; stu1.name = "张三"; stu1.id =2; stu1.score = 100; stu2.name = "李四"; stu2.id = 1; stu2.score = 90; stu3.name = "小明"; stu3.id = 3; stu3.score = 80; stuSet.insert(&stu1); stuSet.insert(&stu2); stuSet.insert(&stu3); Student stuTem; stuTem.score = 80; stuTem.id = 3; Student* stuTempPtr; set<Student*, studentSortCriterion>::iterator iter; iter = stuSet.find(&stuTem); if(iter != stuSet.end()) {   cout << (*iter)->name << endl; }
       else {   cout << "Cannot find the student!" << endl; } for(std::set<Student*,studentSortCriterion>::iterator it = stuSet.begin();it!=stuSet.end();it++ ){ std::cout<<(*it)->name<<endl; } }

    上面程序会根据学生ID先进行排名然后再根据分数进行排名,排序准则需要满足以下要求,摘自C++标准库第二版:

    输出结果:

    小明
    小明
    张三
    李四

  • 相关阅读:
    roundabout插件使用(3d旋转轮播图)兼容IE8
    css实现定高的元素在不定高的容器中水平垂直居中(兼容IE8及以上)
    jq点击小图 弹出大图(更新版)
    pc端页面在移动端显示问题
    swiper横向轮播--3d
    swiper横向轮播(兼容IE8)
    windows 7安装apache
    从SDP中至少要看到那些东西?
    FS拓展设置
    Freeswitch 入门
  • 原文地址:https://www.cnblogs.com/hong2016/p/6700146.html
Copyright © 2011-2022 走看看