使用自定义比较器传递地图功能

Thu*_*ext 1 c++ dictionary function c++11

我有一个带有自定义比较器的STL映射,我希望将其传递给函数,但该函数无法识别自定义比较器.

试图在主要功能中访问地图.

我在代码中列出了两次尝试.

#include <iostream>
#include <string>
#include <map>

// Error: cmpByStringLength is not recognized (both times)
void funcOut(std::map<std::string, int, cmpByStringLength> myMap)
{
  for (std::map<std::string, int, cmpByStringLength>::iterator it = myMap.begin(); it != myMap.end(); ++it)
  {
    std::cout << it->first << " => " << it->second << std::endl;
  }
}

int main()
{
  // Reverse sort by length
  struct cmpByStringLength {
    bool operator()(const std::string& a, const std::string& b) const {
      return a.length() > b.length();
    }
  };

  std::map<std::string, int, cmpByStringLength> myMap;
  myMap.emplace("String 1", 5);
  myMap.emplace("String 123", 10);

  funcOut(myMap);

  // Working
  for (std::map<std::string, int, cmpByStringLength>::iterator it = myMap.begin(); it != myMap.end(); ++it)
  {
    std::cout << it->first << " => " << it->second << std::endl;
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 5

您只能在声明后使用名称,并且只有在范围内时才使用.您的比较器类型的范围是main,因此您只能在该函数中使用它.将定义移出main全局命名空间(或者如果您愿意,可以移动到另一个命名空间中),以使其在其他函数中可用.

或者,您可以将另一个函数作为模板,因此它可以使用任何地图类型:

template <typename Map>
void funcOut(Map const & myMap) {
    // your code here
}
Run Code Online (Sandbox Code Playgroud)