fork(1) download
  1. #include "stdio.h"
  2. #include <iostream>
  3. #include <string>
  4. #include <chrono>
  5. #include <vector>
  6. #include <map>
  7. #include <algorithm>
  8.  
  9. using namespace std::chrono;
  10. using namespace std;
  11.  
  12. // create vector holding desired ordering
  13. vector<string> order({ "a", "d", "i", "n", "ns", "ne", "vl", "rr" });
  14.  
  15. // create sort function for vector of pairs
  16. bool comparator1(const pair<string, string> &s1, const pair<string, string> &s2) {
  17. // find() - it.begin() gives you the index number.
  18. int a = find(order.begin(), order.end(), s1.first) - order.begin();
  19. int b = find(order.begin(), order.end(), s2.first) - order.begin();
  20. return a < b; // lower index < higher index
  21. };
  22.  
  23.  
  24.  
  25. bool comparator2(const pair<string, string> &s1, const pair<string, string> &s2) {
  26. // find() - it.begin() gives you the index number.
  27. auto a = std::make_tuple(s1.first =="a", s1.first =="d", s1.first =="i", s1.first =="n", s1.first =="ns", s1.first =="ne", s1.first =="vl", s1.first =="rr");
  28. auto b = std::make_tuple(s2.first =="a", s2.first =="d", s2.first =="i", s2.first =="n", s2.first =="ns", s2.first =="ne", s2.first =="vl", s2.first =="rr");
  29. return a < b; // lower index < higher index
  30. };
  31.  
  32.  
  33.  
  34. vector<pair<string, string>> vp ={ { "a","legato" },{ "vl","3" },{ "i", "3" },{ "rr","2" } };
  35.  
  36. void sortWithVector() {
  37. sort(vp.begin(), vp.end(), comparator1);
  38. }
  39.  
  40. void sortWithTuple() {
  41. sort(vp.begin(), vp.end(), comparator2);
  42. }
  43.  
  44. int main()
  45. {
  46. high_resolution_clock::time_point t1;
  47. high_resolution_clock::time_point t2;
  48. double duration;
  49.  
  50.  
  51.  
  52.  
  53. t1 = high_resolution_clock::now();
  54.  
  55. for (int i=0; i < 10000; ++i) sortWithVector();
  56.  
  57. t2 = high_resolution_clock::now();
  58. duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
  59. cout << duration/1000.0 << "ms" << endl;
  60.  
  61.  
  62.  
  63.  
  64. t1 = high_resolution_clock::now();
  65.  
  66. for (int i=0; i < 10000; ++i) sortWithTuple();
  67.  
  68. t2 = high_resolution_clock::now();
  69. duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
  70. cout << duration/1000.0 << "ms" << endl;
  71.  
  72. return 0;
  73. }
Success #stdin #stdout 0.04s 3420KB
stdin
Standard input is empty
stdout
7.553ms
31.585ms