C ++ 11 Lambda自定义比较器减慢排序

时间:2017-09-26 02:58:18

标签: sorting c++11 lambda

自定义lambda Comparator比普通函数c ++ 11慢。我经历了几次。但是,仍然无法弄清楚为什么会这样。有没有人经历过这个并知道其背后的原因?

    #include <bits/stdc++.h>
    using namespace std;

    const int N = 1e4 + 1;
    vector<int> v(N);
    vector<int> sorted(N);
    map<int, int> counts;
    long long start;

    void startClock() {
        start = clock();
    }

    void stopClock() {
        cout << float( clock () - start ) /  CLOCKS_PER_SEC << endl;
    }

    void copyOriginal() {
        for (int i = 0; i < N; ++i)
            sorted[i] = v[i];
    }

    void sortWLambda(map<int, int>& counts) {
        cout << "sorting with lambda" << endl;
        sort(sorted.begin(), sorted.end(), [counts](const int& a, const int& b) {
            if (*counts.find(a) != *counts.find(b)) return *counts.find(a) < *counts.find(b);
            return a < b;
        });
    }

    bool comparator(const int& a, const int& b) {
        if (*counts.find(a) != *counts.find(b)) return *counts.find(a) < *counts.find(b);
        return a < b;
    }

    void sortWoLambda() {
        cout << "sorting w/o lambda" << endl;
        sort(sorted.begin(), sorted.end(), comparator);
    }

    int main() {
        for (int i = 0; i < N; ++i) {
            int num = rand() % 1234;
            counts[num]++;
            v[i] = num;
        }

        copyOriginal();
        startClock();
        sortWLambda(counts);
        stopClock();

        copyOriginal();
        startClock();
        sortWoLambda();
        stopClock();

        return 0;
    }
  

使用lambda 6.28秒进行排序

     

用λ0.7秒分选

1 个答案:

答案 0 :(得分:0)

通过引用传递了lambda的差异。

我试过了..

        sort(sorted.begin(), sorted.end(), [&counts](const int& a, const int& b) {
            if (*counts.find(a) != *counts.find(b)) return *counts.find(a) < *counts.find(b);
            return a < b;
        });

现在这与正常功能相同

Passing by constant reference in the lambda capture list这对我也有帮助!