I have a vector of pairs that I want to be stable sorted only by the key (which may occur multiple times). I do not use a multimap for this, because it is not explicitly stable. Therefore, I supply a custom compare function to stable_sort. I'm struggling now with templatizing this function. A brief test implementation follows to show you the use case:
#include <iostream>
#include <algorithm>
#include <vector>
#include "test.h"
using namespace std;
int main() {
typedef pair<int, int> TPair;
vector<TPair> data(10);
data[0] = make_pair(7, 1);
data[1] = make_pair(3, 2);
data[2] = make_pair(8, 0);
data[3] = make_pair(5, 1);
data[4] = make_pair(3, 1);
data[5] = make_pair(2, 0);
data[6] = make_pair(7, 0);
data[7] = make_pair(6, 0);
data[8] = make_pair(5, 0);
data[9] = make_pair(3, 0);
stable_sort(data.begin(), data.end(), comp1);
for (unsigned int i = 0; i < 10; ++i) {
cout << data[i].first << "\t" << data[i].second << endl;
}
return 0;
}
The supplied sorting function is available in test.h:
#include <vector>
#ifndef TEST_H_
#define TEST_H_
using namespace std;
bool comp1(pair<int, int> const & a, pair<int, int> const & b) {
return a.first < b.first;
}
template <typename TElemA, typename TElemB>
bool comp2(pair<TElemA, TElemB> const & a, pair<TElemA, TElemB> const & b) {
return a.first < b.first;
}
template <typename TPair>
bool comp3(TPair const & a, TPair const & b) {
return a.first < b.first;
}
#endif
comp1works well, nothing to complain. First I tried to templatize the elements of the pairs:comp2doesn't work:test.cpp:25:3: error: no matching function for call to 'stable_sort'.comp3fails with the same error message ascomp2.
What is wrong with this template function?