使用sort函数根据函数对列表进行排序

时间:2012-12-13 02:28:42

标签: c++ list sorting g++

我试图使用排序函数对列表进行排序,其中包含比较第二个值的对。这就是我正在使用的:

std::sort(score_list.begin(), score_list.end(), compare_pair);

这是排序功能:

bool Highscore::compare_pair (std::pair<std::string, int> first, std::pair<std::string, int> second)

{
  if (first.second<second.second) return true;
  else return false;
}

我收到此错误消息:

error: no matching function for call to ‘sort(std::list<std::pair<std::basic_string<char>, int> >::iterator, std::list<std::pair<std::basic_string<char>, int> >::iterator, <unresolved overloaded function type>)’

有什么建议吗?感谢

3 个答案:

答案 0 :(得分:3)

您无法直接将成员函数作为比较器传递。使用函数时,实际传递的是指向函数的指针 - 但指向函数的指针完全与指向成员函数的指针不同。

C ++ 98/03有几个名为mem_funmem_fun_ref的适配器(有点)处理这个问题。

C ++ 11添加mem_fn并弃用mem_funmem_fun_ref。假设你有一个足够新的编译器来包含它,那么它使用起来会容易得多。

但是,如果你的编译器是新的,它可能还包括lambdas,它可以使任务相当清晰,因为你可以使用一个“就地”的函数对象定义来处理比较:

typedef std::pair<std::string, int> data_t;

std::sort(score_list.begin(), score_list.end(),
    [](data_t const &a, data_t const &b) { 
        return a.second < b.second; 
    });

如果谷歌有类似“C ++ 11 lambda”的东西,你应该找到更多关于此的信息(其中大部分肯定会直接回到这里)。

答案 1 :(得分:2)

此外,您几乎肯定希望通过const引用而不是值来将对传递给sort函数。

static bool Highscore::compare_pair (const std::pair<std::string, int> &first, const std::pair<std::string, int> &second)

typedef是你的朋友。

答案 2 :(得分:1)

如果要对std::list进行排序,则应使用std::list::sort成员函数。 std::sort算法需要随机访问迭代器std::list仅提供 bidrectional迭代器