【问题标题】:Passing map with custom comparator to function将带有自定义比较器的地图传递给函数
【发布时间】:2015-04-15 12:51:19
【问题描述】:

我有一个带有自定义比较器的 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;
}

【问题讨论】:

  • 你需要将cmpByStringLength定义放在funcOut函数之上
  • 将文件顶部的结构移到函数上方。像其他任何事情一样,您至少需要一个声明(在这种情况下是一个定义)才能使用。
  • 好的,现在可以了!谢谢。

标签: c++ function c++11 dictionary


【解决方案1】:

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

或者,您可以将另一个函数设为模板,这样它就可以与任何地图类型一起使用:

template <typename Map>
void funcOut(Map const & myMap) {
    // your code here
}

【讨论】:

  • 啊,我试过了,但是这给了我某种过载错误,但是将它移到最顶部,在函数上方有效!
  • @CGuy:是的,正如我所说的,你必须在使用前声明它。
  • 如果我必须在多个文件和类的方法之间使用映射声明和自定义比较器,我应该在哪里理想地放置它?单独上课?
  • @CGuy:如果在多个文件中需要它们,那么您将定义该类,如果您真的想要一个全局变量,请在标题中声明它extern。从每个需要它的文件中包含它,并在源文件中定义变量(不带extern)。
【解决方案2】:

使用模板,因为我是一个懒惰的 c++ 开发人员(我不需要担心很多细节......)我会这样做......

template <typename MapType>
void funcOut(MapType& myMap)
{
  for (auto& p : myMap)
  {
    std::cout << p.first << " => " << p.second << std::endl;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2011-06-05
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多