c++ - 带计数器的谓词函数
问题描述
如何制作计算排序算法中迭代次数的谓词函数?我想我应该创建一个返回 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;
}
解决方案
这就是我使用 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 );
推荐阅读
- sabre - 我如何访问 sabre Soap API 中的队列
- logging - 在包含 dropwizard 的应用程序中从 logback 迁移到 log4j2
- android - 在 Direction API 中获取 google map API 问题
- gcc - 使用 gcc 和 as 在 ARM 上组装 MULS 指令
- excel - 如何通过 VBA 在单元格中输入文本和公式?
- jmeter - 如何在 Jmeter 的包含控制器中设置相对文件路径?
- json - 清理ansible上的var输出以在文件上使用它
- python - 从索引列表结合切片的 numpy 花式索引
- python - Django将数据传递给html
- c# - 如何在 c# asp.net 中使用 crud 操作创建 Windows 服务