c++ - 如何重载自定义 std::sort 比较函数?

标签 c++ sorting vector stdvector std-pair

当使用 std::sort 时,如何重载我正在使用的自定义比较函数?

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>

class Misc {
public:
  // Comment out the next three lines to compile without problems.
  static bool sortPair(const std::pair<int, int> &a, const std::pair<int, int> &b){
    return a.first < b.first;
  }
  static bool sortPair(const std::pair<double, std::string> &a, const std::pair<double, std::string> &b){
    return a.first < b.first;
  }
};

int main () {
  std::vector<std::pair<double, std::string> > u;
  u.push_back(std::make_pair(10.0, "ten"));
  u.push_back(std::make_pair(5.0, "five"));
  u.push_back(std::make_pair(1.0, "one"));

  std::sort(u.begin(), u.end(), Misc::sortPair);

  for (unsigned int i=0; i< u.size(); i++){
    std::cout << u.at(i).first << std::endl;
  }

  return 0;
}

我无法编译它,因为它提示:

unresolved overloaded function type

我可以看到使用 sortPair 可能有些不明确,但我假设编译器能够根据与 vector u 关联的类型来解决这个问题。有什么方法可以指定使用哪个函数/方法来消除问题的歧义?

目前,注释掉第一个 sortPair 函数允许编译代码并产生正确的排序输出。当然,这是因为不再有歧义了。

最佳答案

您可以改用仿函数:

class Misc {
  public:
    // static bool sortPair(const std::pair<int, int> &a, const std::pair<int, int> &b);
    // static bool sortPair(const std::pair<double, std::string> &a, const std::pair<double, std::string> &b);
    bool operator() (const std::pair<int, int> &a, const std::pair<int, int> &b) { // something 
        return true;
    }
    bool operator() (const std::pair<double, std::string> &a, const std::pair<double, std::string> &b) { // something 
        return true;
    }
} misc;

int main()
{
    std::vector<std::pair<double, std::string> > u;
    std::vector<std::pair<int, int> > u2;
    //Fill vector u with data
    std::sort(u.begin(), u.end(), misc);
    std::sort(u2.begin(), u2.end(), misc);
    return 0;
}

关于c++ - 如何重载自定义 std::sort 比较函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20039912/

相关文章:

java - 为什么继承每个类然后简单地创建派生类的单个对象来执行 oop 中的所有操作是一种不好的做法?

c++ - 构造函数调用时的圆括号与大括号

c++ - 用于 C++ 的文本布局引擎 API

java - 插入 map 时按值保留顺序

sql - 如何为 postgresql 中的表的每一行递增每个时间戳?

c++ - GlGenTextures 不断返回 0

javascript - 如何通过LI的data-title参数对UL列表进行排序?

c++ - 对象指针赋值的指针 vector 的一个元素

vector - Clojure 从指定位置的 Vector 中删除项目

c++ - 带有 vector 对象 C++ 的快速排序函数