fork download
  1. #include <string>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <iostream>
  5.  
  6. struct Person {
  7. std::string name;
  8. int age;
  9. };
  10.  
  11. // Compare using std::string's less-than operator.
  12. bool operator< (const Person& lhs, const Person& rhs) {
  13. return lhs.name < rhs.name;
  14. }
  15.  
  16. int main() {
  17. // Create vector of Person objects and initialize with some random names.
  18. std::vector<Person> crew { {"Bob", 45}, {"Steve", 25}, {"Andy", 30} };
  19.  
  20. // Sort vector using < operator.
  21. std::sort(begin(crew), end(crew));
  22.  
  23. // Output all elements in vector.
  24. for(const auto& p : crew) {
  25. std::cout << p.name << " is " << p.age << " years old" << std::endl;
  26. }
  27. }
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
Andy is 30 years old
Bob is 45 years old
Steve is 25 years old