当使用 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/