上次面阿里巴巴。面试官问了我这样一个问题,“C++ STL中的set是如何实现的”。当时只答了二叉树,回来查下书,原来一般是红黑树,后悔没好好记住啊。。。
接着,面试官又考了我一道这样的编程题:定义一个Student结构体,包括name和age等数据,要求编程实习在set中查找一个name == "张三",age == 13的操作。
本来set自己用得不多,当时一下懵了。回来查阅《C++标准程序库》这本书,自己试着实现了下。
- #include<iostream>
- #include<set>
- usingnamespacestd;
- /*Student结构体*/
- structStudent{
- stringname;
- intage;
- stringsex;
- };
- /*“仿函数"。为Studentset指定排序准则*/
- classstudentSortCriterion{
- public:
- booloperator()(constStudent&a,constStudent&b)const{
- /*先比较名字;若名字相同,则比较年龄。小的返回true*/
- if(a.name<b.name)
- returntrue;
- elseif(a.name==b.name){
- if(a.age<b.age)
- returntrue;
- else
- returnfalse;
- }else
- returnfalse;
- }
- };
- intmain()
- {
- set<Student,studentSortCriterion>stuSet;
- Studentstu1,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的缘故。
- */
- StudentstuTemp;
- stuTemp.name="张三";
- stuTemp.age=13;
- set<Student,studentSortCriterion>::iteratoriter;
- iter=stuSet.find(stuTemp);
- if(iter!=stuSet.end()){
- cout<<(*iter).name<<endl;
- }else{
- cout<<"Cannotfinethestudent!"<<endl;
- }
- return0;
- }