fork download
  1. #include <map>
  2. #include <vector>
  3. #include <iostream>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. const int N = 1e4 + 1;
  8. vector<int> v(N);
  9. vector<int> sorted(N);
  10. map<int, int> counts;
  11. long long start;
  12.  
  13. void startClock() {
  14. start = clock();
  15. }
  16.  
  17. void stopClock() {
  18. cout << float( clock () - start ) / CLOCKS_PER_SEC << endl;
  19. }
  20.  
  21. void copyOriginal() {
  22. for (int i = 0; i < N; ++i)
  23. sorted[i] = v[i];
  24. }
  25.  
  26. void sortWLambda(map<int, int>& counts) {
  27. cout << "sorting with lambda" << endl;
  28. sort(sorted.begin(), sorted.end(), [&counts](const int& a, const int& b) {
  29. if (*counts.find(a) != *counts.find(b)) return *counts.find(a) < *counts.find(b);
  30. return a < b;
  31. });
  32. }
  33.  
  34. bool comparator(const int& a, const int& b) {
  35. if (*counts.find(a) != *counts.find(b)) return *counts.find(a) < *counts.find(b);
  36. return a < b;
  37. }
  38.  
  39. void sortWoLambda() {
  40. cout << "sorting w/o lambda" << endl;
  41. sort(sorted.begin(), sorted.end(), comparator);
  42. }
  43.  
  44. int main() {
  45. for (int i = 0; i < N; ++i) {
  46. int num = rand() % 1234;
  47. counts[num]++;
  48. v[i] = num;
  49. }
  50.  
  51. copyOriginal();
  52. startClock();
  53. sortWLambda(counts);
  54. stopClock();
  55.  
  56. copyOriginal();
  57. startClock();
  58. sortWoLambda();
  59. stopClock();
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0.03s 16072KB
stdin
Standard input is empty
stdout
sorting with lambda
0.019469
sorting w/o lambda
0.014591