【发布时间】:2013-12-01 03:19:19
【问题描述】:
使用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;
}
我无法编译它,因为它抱怨:
未解析的重载函数类型
我可以看到使用sortPair 可能有点模棱两可,但我假设编译器能够根据与向量u 关联的类型来解决这个问题。有什么方法可以让我指定使用哪个函数/方法来消除问题的歧义?
目前,注释掉第一个 sortPair 函数可以编译代码并生成正确的排序输出。当然,这是因为它不再模棱两可了。
【问题讨论】:
-
为什么比较函数的第二个参数不是 const 引用?它缺少
&。 -
要手动解决过载问题,请使用
static_cast。 -
我已经编辑了我的问题。谢谢。在这种情况下如何使用“static_cast”?
-
您必须手动将其转换为正确的函数指针类型,以帮助编译器消除调用歧义。
标签: c++ sorting vector stdvector std-pair