カスタム データ構造のベクトルを並べ替えるのに役立つ比較関数オブジェクトを作成したいと考えています。テンプレートを同時に使用しているため、正確に実装する必要がある場所と必要な追加コードを見つけるのに苦労しています。以下のコードのほとんどは無視できます。完全を期すために含まれていますが、比較関数オブジェクトは の最後で使用されます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
}
};