阿里Set

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

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

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

  1. #include<iostream>
  2. #include<set>
  3. usingnamespacestd;
  4. /*Student结构体*/
  5. structStudent{
  6. stringname;
  7. intage;
  8. stringsex;
  9. };
  10. /*“仿函数"。为Studentset指定排序准则*/
  11. classstudentSortCriterion{
  12. public:
  13. booloperator()(constStudent&a,constStudent&b)const{
  14. /*先比较名字;若名字相同,则比较年龄。小的返回true*/
  15. if(a.name<b.name)
  16. returntrue;
  17. elseif(a.name==b.name){
  18. if(a.age<b.age)
  19. returntrue;
  20. else
  21. returnfalse;
  22. }else
  23. returnfalse;
  24. }
  25. };
  26. intmain()
  27. {
  28. set<Student,studentSortCriterion>stuSet;
  29. Studentstu1,stu2;
  30. stu1.name="张三";
  31. stu1.age=13;
  32. stu1.sex="male";
  33. stu2.name="李四";
  34. stu2.age=23;
  35. stu2.sex="female";
  36. stuSet.insert(stu1);
  37. stuSet.insert(stu2);
  38. /*构造一个测试的Student,可以看到,即使stuTemp与stu1实际上并不是同一个对象,
  39. *但当在set中查找时,仍会查找成功。这是因为已定义的studentSortCriterion的缘故。
  40. */
  41. StudentstuTemp;
  42. stuTemp.name="张三";
  43. stuTemp.age=13;
  44. set<Student,studentSortCriterion>::iteratoriter;
  45. iter=stuSet.find(stuTemp);
  46. if(iter!=stuSet.end()){
  47. cout<<(*iter).name<<endl;
  48. }else{
  49. cout<<"Cannotfinethestudent!"<<endl;
  50. }
  51. return0;
  52. }

猜你喜欢

转载自vergilwang.iteye.com/blog/2011234
set