fork download
  1. #include <string>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <iostream>
  5.  
  6. class Foo
  7. {
  8. private:
  9. std::string name;
  10. int age;
  11.  
  12. public:
  13. Foo(const char *_name, int _age)
  14. : name(_name)
  15. , age(_age)
  16. {}
  17.  
  18. const char *getName(void) const { return name.c_str(); }
  19. int getAge(void) const { return age; }
  20.  
  21. };
  22.  
  23. bool compareAge(Foo *foo1, Foo *foo2)
  24. {
  25. return foo1->getAge() < foo2->getAge();
  26. }
  27.  
  28. namespace my
  29. {
  30. typedef std::vector<Foo *> vector;
  31. }
  32.  
  33. using my::vector;
  34. using std::sort;
  35. using std::cout;
  36. using std::endl;
  37.  
  38. int main(void)
  39. {
  40. Foo foo1("A", 10);
  41. Foo foo2("B", 30);
  42. Foo foo3("C", 5);
  43. vector foo_v;
  44.  
  45. foo_v.insert(foo_v.end(), &foo1);
  46. foo_v.insert(foo_v.end(), &foo2);
  47. foo_v.insert(foo_v.end(), &foo3);
  48.  
  49. sort(foo_v.begin(), foo_v.end(), compareAge);
  50.  
  51. // Print out the contents of foo_v.
  52. for(vector::iterator it(foo_v.begin()); it != foo_v.end(); ++it)
  53. {
  54. Foo *&pFoo = *it;
  55. cout << pFoo->getName() << endl;
  56. }
  57. }
  58.  
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
C
A
B