pair <> question
Oct 17, 2010 at 2:51pm UTC
Hi there,
Let's say we have the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<string, int > Data;
class Compare
{
public :
bool operator ()(const Data& el1, const Data& el2) const
{
return lessK(el1.first, el2.first);
}
bool operator () (const Data& el1, const Data::first_type& k) const
{
return lessK(el1.first, k);
}
bool operator ()(const Data::first_type& k, const Data& el2)
{
return lessK(k, el2.first);
}
private :
bool keyLess(const Data::first_type& k1, const Data::first_type& k2) const
{
return k1 < k2;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<Data> dataVector;
// .. do some insertion
sort(dataVector.begin(), dataVector.end(),Compare());
// ... do something again
return 0;
}
This will work as long as same pair is in use, if there is another pair defined, pair<int, string>, Compare class should be re-written.
My question is – is there better approach to come up with ‘general’ class which could cover different cases? One of the approaches was :
1 2 3 4 5 6 7 8
template <typename T, typename T2> class DataCompareTemplate
{
public :
bool operator ()(const T& el1, const T& el2) const
{
return el1.first < el2.first;
}
};
As you could see only single case, where T passed as argument is covered and not where 'T::firts_type&' is passed
Oct 17, 2010 at 5:31pm UTC
I think you could define a global templated function operator<():
1 2 3 4 5
template <typename T>
bool operator <(const T& a, const T& b)
{
return a.first < b.first;
}
That should work for any pair type.
Topic archived. No new replies allowed.