I’m trying to write a custom cmp function for a map, a simple one that does the comparison over the second element of the map. I’d like to have the function as a template, but I can’t figure out how to pass the map’s .first and .second types along to my cmp function. My non-working code is below, which will clearly fail since the type of T1 and T2 are not passed along:
#include <map>
#include <vector>
#include <algorithm>
template<class T1, class T2>
bool pairCompare(const std::pair<T1,T2> & x,
const std::pair<T1,T2> & y) {
return x.second < y.second;
}
template<class T1>
typename T1::iterator map_max_element(const T1 & A) {
// How do I pass the type to pairCompare?
return std::max_element(A.begin(), A.end(), pairCompare<?????>);
}
int main() {
std::map<std::vector<double>, int> A;
map_max_element(A);
return 0;
}
std::maphas a nested type calledvalue_typewhich is actually a typedef ofstd::pair<const K, V>. Andstd::pairhas two nested typesfirst_typeandsecond_type. Use this info as:Note that in your code the return type is wrong. It should be
const_iterator, rather thaniterator, because in the functionAis const map. Hence what you can get from it isconst_iterator. 🙂Or you could simply write the compare function as:
And use it as: