WHCSRL 技术网

C++ set 排序 修改元素之后不会改变原来的排序

  1. #include <iostream>
  2. #include <set>
  3. #include <algorithm>
  4. using namespace std;
  5. /*Student结构体*/
  6. struct Student {
  7. string name;
  8. int id;
  9. int score;
  10. };
  11. /*“仿函数"。为Student set指定排序准则*/
  12. class studentSortCriterion {
  13. public:
  14. /*类型要与set容器类型一致*/
  15. bool operator()( const Student *a, const Student *b ) const
  16. {
  17. // 成绩相等,按照id从小到大排;成绩不相等,按照成绩从大到小排
  18. return( (a->score == b->score) ? (a->id < b->id) : (a->score > b->score) );
  19. }
  20. };
  21. int main()
  22. {
  23. set<Student*, studentSortCriterion> stuSet;
  24. set<Student*> stus;
  25. Student stu1, stu2, stu3;
  26. stu1.name = "张三";
  27. stu1.id = 1;
  28. stu1.score = 100;
  29. stu2.name = "李四";
  30. stu2.id = 2;
  31. stu2.score = 90;
  32. stu3.name = "小明";
  33. stu3.id = 3;
  34. stu3.score = 100;
  35. stuSet.insert( &stu1 );
  36. stuSet.insert( &stu2 );
  37. stuSet.insert( &stu3 );
  38. /* 遍历 */
  39. for ( std::set<Student*, studentSortCriterion>::iterator it = stuSet.begin(); it != stuSet.end(); it++ )
  40. {
  41. std::cout << (*it)->name << (*it)->score << endl;
  42. }
  43. stu3.score = 200;
  44. /* 遍历 */
  45. for ( std::set<Student*, studentSortCriterion>::iterator it = stuSet.begin(); it != stuSet.end(); it++ )
  46. {
  47. std::cout << (*it)->name << (*it)->score << endl;
  48. }
  49. }