fork download
  1. #include <vector>
  2. #include <string>
  3.  
  4. #include <algorithm>
  5. #include <functional>
  6. #include <iterator>
  7.  
  8. #include <iostream>
  9.  
  10. // ------------------------------------
  11.  
  12. typedef std::vector<std::string> string_vector;
  13.  
  14. // Functor created by the wizard
  15. struct size_sorter
  16. : public std::binary_function<std::string, std::string, bool>
  17. {
  18. bool operator() (const std::string &left, const std::string &right) const
  19. {
  20. return (left.size() < right.size());
  21. }
  22. };
  23.  
  24. void test_functor_solution(string_vector sv)
  25. {
  26. std::sort(sv.begin(), sv.end(), size_sorter());
  27. std::copy(sv.begin(), sv.end(), std::ostream_iterator<std::string>(std::cout, " "));
  28. }
  29.  
  30. // ------------------------------------
  31.  
  32. void test_lambda_solution(string_vector sv)
  33. {
  34. // Sort with lambda created by the wizard
  35. std::sort(sv.begin(), sv.end(),
  36. [] (const std::string &left, const std::string &right) -> bool
  37. {
  38. return (left.size() < right.size());
  39. }
  40. );
  41.  
  42. std::copy(sv.begin(), sv.end(), std::ostream_iterator<std::string>(std::cout, " "));
  43. }
  44.  
  45. // ------------------------------------
  46.  
  47. int main()
  48. {
  49. string_vector test_data;
  50.  
  51. test_data.push_back("george");
  52. test_data.push_back("nick");
  53. test_data.push_back("peter");
  54.  
  55. test_functor_solution(test_data);
  56. std::cout << std::endl;
  57. test_lambda_solution(test_data);
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0s 3036KB
stdin
Standard input is empty
stdout
nick peter george 
nick peter george