fork download
  1. #include <cstring>
  2. class Item
  3. {
  4. private:
  5. int id;
  6. char name[32];
  7.  
  8. public:
  9. Item(const int id = 0, const char *name = nullptr)
  10. {
  11. this->id = id;
  12.  
  13. if(!name)
  14. ::strcpy(this->name, "");
  15. else
  16. ::strcpy(this->name, name);
  17. }
  18.  
  19. const int getId() const
  20. {
  21. return id;
  22. }
  23.  
  24. const char* getName() const
  25. {
  26. return name;
  27. }
  28.  
  29. bool operator<(const Item another) const
  30. {
  31. return this->id < another.id;
  32. }
  33.  
  34. bool operator>(const Item another) const
  35. {
  36. return this->id > another.id;
  37. }
  38. };
  39.  
  40. #include <cstdio>
  41. #include <vector>
  42. #include <algorithm>
  43.  
  44. using namespace std;
  45. typedef vector<Item> ItemVector;
  46.  
  47. int main(int argc, char **argv)
  48. {
  49. ItemVector itemVector;
  50.  
  51. itemVector.push_back(Item(2, "アイテム2"));
  52. itemVector.push_back(Item(4, "アイテム4"));
  53. itemVector.push_back(Item(1, "アイテム1"));
  54. itemVector.push_back(Item(3, "アイテム3"));
  55. itemVector.push_back(Item(0, "アイテム0"));
  56.  
  57. stable_sort(itemVector.begin(), itemVector.end(), [](const Item& a, const Item& b) { return a < b; } );
  58.  
  59. for(ItemVector::iterator iter = itemVector.begin();
  60. iter != itemVector.end();
  61. ++iter) {
  62. printf("%d: %s\n", iter->getId(), iter->getName());
  63. }
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
0: アイテム0
1: アイテム1
2: アイテム2
3: アイテム3
4: アイテム4