首页 > 解决方案 > 带计数器的谓词函数

问题描述

如何制作计算排序算法中迭代次数的谓词函数?我想我应该创建一个返回 lambda 的函数,因为: auto p1 = predicate_with_counter(predicate1, counter);。但我不知道该怎么做。在问题的文本中,它说 main 函数应该保持原样,因此不允许更改 main

#include <vector>
#include <iostream>
#include <algorithm>

// predicate_with_counter() ???

bool predicate1(double a, double b){
   return a > b;
}

int main(){
   using namespace std;
   size_t counter;
   vector<double> v1{2,4,0,-1,5};
   auto p1 = predicate_with_counter(predicate1, counter);
   sort(begin(v1), end(v1), p1);
   cout << "Number of comparisons in sorting of v1 : " << counter << endl;

   return 0;
}

标签: c++

解决方案


这就是我使用 lambda 表达式解决您的问题的方法:

#include <vector>
#include <iostream>
#include <algorithm>

int main() {
    using namespace std;
    size_t counter=0;
    vector<double> v1{ 2,4,0,-1,5 };
    sort(begin(v1), end(v1), [&counter](double a, double b)
        {
            counter++;
            return a > b;
        });
    cout << "Number of comparisons in sorting of v1 : " << counter << endl;

    return 0;
}

回答你的问题,如果你想把它作为一个函数,你可以使用 auto:

auto count_comparisons = [&counter](double a, double b)
    {
        counter++;
        return a > b;
    };
 sort(begin(v1), end(v1),count_comparisons );

推荐阅读