c++ - 如何使用 std::sort 根据某个函数返回的值对数组进行排序,同时传递要排序的数组元素?
问题描述
如何使用 std::sort 根据某个函数返回的值对数组进行排序,同时传递要排序的数组元素?
class Board{
//members
};
int score(int num,Board b){
return b.evaluate(num);
//lets say score() function returns an evaluation based
//on num and Board type object b.
}
void main(){
Board b;
int num_array[10]{0,1,2,3,4,5,6,7,8,9};
std::sort(num_array.begin(),num_array.end());
//how to use std::sort to sort num_array based on values returned
//by score() while passed elements of num_array
}
有没有办法将函数作为 std::sort 中的第三个参数传递,还是需要以其他方式解决?
解决方案
使用 lambda,并通过引用捕获板以在其中使用:
#include <algorithm>
#include <cstdio>
#include <iterator>
struct Board {
int grades[10] = {90, 80, 70, 60, 50, 40, 30, 20, 10, 0};
int evaluate(int i) const { return grades[i]; }
};
int score(int i, Board const& board) { return board.evaluate(i); }
int main() {
Board b;
int num_array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::sort(std::begin(num_array), std::end(num_array),
[&b](auto const& e1, auto const& e2) {
return score(e1, b) < score(e2, b);
});
for (auto& e : num_array) std::printf("%d ", e);
std::putchar('\n');
}
推荐阅读
- javascript - React 中是否有替代 querySelectorAll 的方法?
- pandas - 如何有效地使用字典或其他方法来清理数据
- function - 将 jupyter 小部件文本框链接到绘制图形的函数
- node.js - npm run build failed,这里有什么问题?
- python - 如何检查来自不同数据框的列值?
- c# - 在 DialogService 上保留 ViewModel 实例
- python - Pandas - 我想要的只是一个单一的系列值输出,而不是其他元数据
- kotlin - 我需要一个嵌套的密封类吗?
- java - “补充私有方法”如何帮助避免原始类型?
- postgresql - 无法在 PostgreSQL 中创建存储过程:“$$”处或附近未终止的美元引号字符串