阿里Set

上次面阿里巴巴。面试官问了我这样一个问题,“C++ STL中的set是如何实现的”。当时只答了二叉树,回来查下书,原来一般是红黑树,后悔没好好记住啊。。。

接着,面试官又考了我一道这样的编程题:定义一个Student结构体,包括name和age等数据,要求编程实习在set中查找一个name == "张三", age == 13的操作。

本来set自己用得不多,当时一下懵了。回来查阅《C++标准程序库》这本书,自己试着实现了下。

  1. #include <iostream>  
  2. #include <set>  
  3. using namespace std;  
  4.   
  5. /*Student结构体*/  
  6. struct Student {  
  7.     string name;  
  8.     int age;  
  9.     string sex;  
  10. };  
  11.   
  12. /*“仿函数"。为Student set指定排序准则*/  
  13. class studentSortCriterion {  
  14.     public:  
  15.         bool operator() (const Student &a, const Student &b) const {  
  16.             /*先比较名字;若名字相同,则比较年龄。小的返回true*/  
  17.             if(a.name < b.name)  
  18.                 return true;  
  19.             else if(a.name == b.name) {  
  20.                 if(a.age < b.age)  
  21.                     return true;  
  22.                 else  
  23.                     return false;  
  24.             } else  
  25.                 return false;  
  26.         }  
  27. };  
  28.   
  29. int main()  
  30. {  
  31.     set<Student, studentSortCriterion> stuSet;  
  32.   
  33.     Student stu1, stu2;  
  34.     stu1.name = "张三";  
  35.     stu1.age = 13;  
  36.     stu1.sex = "male";  
  37.   
  38.     stu2.name = "李四";  
  39.     stu2.age = 23;  
  40.     stu2.sex = "female";  
  41.   
  42.     stuSet.insert(stu1);  
  43.     stuSet.insert(stu2);  
  44.   
  45.     /*构造一个测试的Student,可以看到,即使stuTemp与stu1实际上并不是同一个对象, 
  46.      *但当在set中查找时,仍会查找成功。这是因为已定义的studentSortCriterion的缘故。 
  47.      */  
  48.     Student stuTemp;  
  49.     stuTemp.name = "张三";  
  50.     stuTemp.age = 13;  
  51.   
  52.     set<Student, studentSortCriterion>::iterator iter;  
  53.     iter = stuSet.find(stuTemp);  
  54.     if(iter != stuSet.end()) {  
  55.         cout << (*iter).name << endl;  
  56.     } else {  
  57.         cout << "Cannot fine the student!" << endl;  
  58.     }  
  59.   
  60.     return 0;  
  61. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值