fork download
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <iostream>
  3. using namespace std;
  4. #include <list>
  5. #include <algorithm>
  6. #include <string>
  7.  
  8. class Hero
  9. {
  10. public:
  11. Hero(int age, int height, string name)
  12. {
  13. this->m_name = name;
  14. this->m_age = age;
  15. this->m_height = height;
  16. }
  17. int m_age;
  18. int m_height;
  19. string m_name;
  20. /* overloading operator == */
  21. bool operator==(const Hero &h) const
  22. {
  23. return m_age == h.m_age && m_name == h.m_name && m_height == h.m_height;
  24. }
  25. };
  26.  
  27. void printList(list<Hero> &L)
  28. {
  29. for (list<Hero>::iterator it = L.begin(); it != L.end(); it++)
  30. {
  31. cout << "姓名:" << (*it).m_name << "|年齡:" << (it)->m_age << "|身高:" << (it)->m_height << endl;
  32. }
  33. }
  34.  
  35. bool listCompare(Hero &h1, Hero &h2)
  36. {
  37. if (h1.m_age == h2.m_age)
  38. {
  39. return h1.m_height > h2.m_height;
  40. }
  41.  
  42. return h1.m_age < h2.m_age;
  43. }
  44.  
  45. void test01()
  46. {
  47. list<Hero> L;
  48. Hero h1(24, 165, "關羽");
  49. Hero h2(35, 175, "劉備");
  50. Hero h3(29, 188, "張飛");
  51. Hero h4(46, 167, "趙雲");
  52. Hero h5(17, 182, "孔明");
  53.  
  54. L.push_back(h1);
  55. L.push_back(h2);
  56. L.push_back(h3);
  57. L.push_back(h4);
  58. L.push_back(h5);
  59.  
  60. printList(L);
  61.  
  62. printf("---------------\n");
  63.  
  64. L.sort(listCompare);
  65.  
  66. printList(L);
  67.  
  68. printf("---------------\n");
  69.  
  70. L.remove(h4);
  71. }
  72.  
  73. int main(int argc, char const *argv[])
  74. {
  75. system("clear");
  76. test01();
  77. return 0;
  78. }
  79.  
Success #stdin #stdout #stderr 0s 4468KB
stdin
Standard input is empty
stdout
姓名:關羽|年齡:24|身高:165
姓名:劉備|年齡:35|身高:175
姓名:張飛|年齡:29|身高:188
姓名:趙雲|年齡:46|身高:167
姓名:孔明|年齡:17|身高:182
---------------
姓名:孔明|年齡:17|身高:182
姓名:關羽|年齡:24|身高:165
姓名:張飛|年齡:29|身高:188
姓名:劉備|年齡:35|身高:175
姓名:趙雲|年齡:46|身高:167
---------------
stderr
TERM environment variable not set.