首页 > 解决方案 > 如何使用 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 中的第三个参数传递,还是需要以其他方式解决?

标签: c++arrayssorting

解决方案


使用 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');
}

推荐阅读