我想创建一个比较函数对象来帮助我对自定义数据结构的 vector 进行排序。由于我同时使用模板,因此我正在努力弄清楚应该在哪里实现它以及需要任何其他代码。下面的大部分代码都可以忽略。包含它是为了完整性,但在 printSummary()
的最后使用了比较函数对象。简而言之,如何实现比较函数对象?
#include<map>
#include<vector>
//#include<iostream>
#include<algorithm>
using namespace std;
template <class T>
class Record{
public:
T item;
int total;
};
template<class T>
bool compare(const Record<T> & a, const Record<T> & b){ //should a come before b?
if(a.total > b.total)
return true;
if(a.total < b.total)
return false;
if(a.total == b.total){
if(a.item < b.item)
return true;
else
return false;
}
}
template <class T>
class Counter{
public:
map<T, int> m;
void printSummary(){
typename map<T, int>::const_iterator itr;
vector< Record<T> > printlist;
Record<T> temp;
int i = 0;
for( itr = m.begin(); itr != m.end(); ++itr ){
temp.item = (*itr).first;
temp.total = (*itr).second;
printlist.push_back(temp);
i++;
}
sort(printlist.begin(), printlist.end(), compare);
//output sorted printlist contents
}
};
最佳答案
在您调用 sort()
时,您正在指定一个函数的名称模板 而不实例化它:
sort(printlist.begin(), printlist.end(), compare);
// ^^^^^^^
函数模板的裸名代表编译器的整个重载集(其中该集包括该模板的所有可能特化)。
要消除歧义,需要实例化compare<>()
为了提供一个函数的地址:
sort(printlist.begin(), printlist.end(), compare<T>);
// ^^^
或者,您可以制作compare
一个仿函数:
struct compare
{
template<class T>
bool operator () (const Record<T> & a, const Record<T> & b)
{
// should a come before b?
if(a.total > b.total)
return true;
if(a.total < b.total)
return false;
if(a.total == b.total){
if(a.item < b.item)
return true;
else
return false;
}
}
};
然后,您可以将其传递给 sort()
这样,无需模板实例化(但您需要创建仿函数的实例,尽管临时的很好,如下所示):
sort(printlist.begin(), printlist.end(), compare());
// ^^^^^^^^^
关于c++ - 如何将 sort() 的比较参数与模板和自定义数据结构一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15988345/