【发布时间】: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