c++ - map 上 max_element 的模板函数需要知道这两种类型

标签 c++ templates stl

我正在尝试为 map 编写一个自定义 cmp 函数,这是一个对 map 的第二个元素进行比较的简单函数。我想将该函数用作模板,但我不知道如何将 map 的 .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;
}

最佳答案

std::map有一个名为 value_type 的嵌套类型这实际上是 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>);
}

请注意,在您的代码中,返回类型是错误的。应该是const_iterator , 而不是 iterator , 因为在函数 A 中是常量映射。因此,您可以从中得到 const_iterator . :-)


或者您可以简单地将比较函数编写为:

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

并将其用作:

return std::max_element(A.begin(), A.end(), pairCompare<typename T::value_type>);

关于c++ - map 上 max_element 的模板函数需要知道这两种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7110105/

相关文章:

c++ - C++ 代码生成的宏替代方案

c++ - 如何显示一种 collat​​z 猜想的二叉树?

c++ - STL迭代器包装器

c++ - STL::vector 无法分配内存 'randomly'

c++ - c++ 中的 std::vector 默认如何释放

c++ - std::string::length() 与 std::string::size()

c++ - 从 C++ 调用带有可选参数的 Fortran 子例程

c++ - 如何避免嵌套模板中的重复模板参数

c++ - 升压::变体 - "no matching function for call"

c++ - 使用 Poco::zip 添加新目录总是给出异常