使用排序功能根据功能对列表进行排序 [英] Using the sort function to sort a list according to a function

查看:128
本文介绍了使用排序功能根据功能对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时通讯尝试使用排序函数来排序列表,我已经包含对比较他们的第二个值。这是我使用的:

  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)返回true;
else返回false;
}

我收到以下错误消息:

 错误:没有匹配函数调用'sort(std :: list< std :: pair< std :: basic_string< char> ;, int>> ;: :iterator,std :: list< std :: pair< std :: basic_string< char>,int>> :: iterator,<未解析的重载函数类型>)'

有什么建议吗?谢谢

解决方案

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

C ++ 98/03有几个适配器,名为 mem_fun mem_fun_ref (有点)处理这个。



C ++ 11增加了 mem_fn 并且弃用 mem_fun mem_fun_ref 。如果你的编译器是新的,那么它可能还会包含lambda表达式,它可能会包含lambda表达式,这可以使任务相当干净,因为你可以通过一个就地定义一个函数对象来处理比较:

  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;
});

如果Google为C ++ 11 lambda之类的东西,你应该找到更多的信息关于这一点(其中大部分几乎肯定会直接导致回到这里)。


im trying to use a sort function to sort a list i have containing pairs comparing their second value. this is what i am using:

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

This is the sort function:

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;
}

and i am getting this error message:

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>)’

Any advice? Thanks

解决方案

You can't pass a member function directly as the comparator. When you use a function, what's actually passed is a pointer to the function -- but a pointer to a function is entirely different from a pointer to a member function.

C++98/03 has a couple of adapters named mem_fun and mem_fun_ref that (sort of) deal with this.

C++11 adds mem_fn and deprecates mem_fun and mem_fun_ref. It's quite a bit easier to use, assuming you have a compiler new enough to include it.

If your compiler is that new, however, it'll probably also include lambdas, which can make the task considerably cleaner, because you can us an "in place" definition of a function object to handle the comparison:

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; 
    });

If you Google for something like "C++11 lambda" you should find quite a bit more information about this (much of which will almost certainly lead directly back here to SO).

这篇关于使用排序功能根据功能对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆