地图上max_element的模板函数需要知道这两种类型

Hoo*_*ked 1 c++ templates stl

我正在尝试为地图编写一个自定义cmp函数,这是一个简单的函数,可以对地图的第二个元素进行比较.我想把这个函数作为模板,但是我无法弄清楚如何将地图.first.second类型传递给我的cmp函数.我的非工作代码在下面,由于T1和T2的类型没有传递,因此显然会失败:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 12

std::map有一个嵌套类型value_type,实际上是一个typedef std::pair<const K, V>.并且std::pair有两种嵌套类型first_typesecond_type.使用此信息:

template<class T>
typename T::const_iterator map_max_element(const T & A) 
{
   typedef typename T::value_type pair_type;
   typedef typename pair_type::first_type K;
   typedef typename pair_type::second_type V;
   return std::max_element(A.begin(), A.end(), pairCompare<K,V>);
}
Run Code Online (Sandbox Code Playgroud)

请注意,在您的代码中,返回类型是错误的.它应该是const_iterator,而不是iterator因为在函数中A是const map.因此,你可以从中得到什么const_iterator.:-)


或者你可以简单地将compare函数写为:

template<class T>
bool pairCompare(const T & x, const T & y) {
  return x.second < y.second; 
}
Run Code Online (Sandbox Code Playgroud)

并将其用作:

return std::max_element(A.begin(), A.end(), pairCompare<typename T::value_type>);
Run Code Online (Sandbox Code Playgroud)