今天在使用自定义的枚举作为unordered_map的键时,提示以下错误:
undefined reference to `std::tr1::hash<v4l2::_VideoFormat>::operator()(v4l2::_VideoFormat) const'
其中_VideoFormat是我定义的枚举。
在网上查了是这样说的:
首先定义模板作为unordered_map的第三个参数:
struct EnumClassHash
{
template <typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
使用:
enum class MyEnum {};
std::unordered_map<MyEnum, int, EnumClassHash> myMap;
这样就简单的解决了各种operator的错误了。
原文链接在这儿:
https://blog.youkuaiyun.com/f120854632/article/details/88343575
https://stackoverflow.com/questions/18837857/cant-use-enum-class-as-unordered-map-key
ps:unordered_map 使用
头文件:
#include <tr1/unordered_map>
命名空间:
using namespace std;
using namespace std::tr1;