【问题标题】:Using the sort function to sort a list according to a function使用 sort 函数根据函数对列表进行排序
【发布时间】:2012-11-30 21:05:06
【问题描述】:

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

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

有什么建议吗?谢谢

【问题讨论】:

    标签: c++ list sorting g++


    【解决方案1】:

    您不能直接将成员函数作为比较器传递。当你使用一个函数时,实际上传递的是一个指向函数的指针——但指向函数的指针完全不同于指向成员函数的指针。 p>

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

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

    但是,如果您的编译器是新的,那么它可能还会包含 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”之类的内容,您应该会找到更多关于此的信息(其中大部分几乎肯定会直接回到 SO)。

    【讨论】:

      【解决方案2】:

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

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

      typedef 是你的朋友。

      【讨论】:

        【解决方案3】:

        如果您要对std::list 进行排序,您应该使用std::list::sort 成员函数。 std::sort 算法需要随机访问迭代器,而std::list 只提供双向迭代器

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-10-28
          • 1970-01-01
          • 2021-11-13
          • 2021-04-21
          • 2021-12-19
          • 2013-06-27
          • 1970-01-01
          相关资源
          最近更新 更多