在set/unordered_set 用自定义类型, 编译失败。 记录下。
在set 中使用自定义类型 mask, 需要提供 std::less<mask> 和等价的方式
set 构造函数的原型
set (const _Compare &__comp, const allocator_type &__a=allocator_type())
如果是自定义变量需要提供 Compare, compare 默认是用std::less. std::less 的默认实现是用 对应类型的 operator < 。
如果同时提供 bool mask::operator<(const mask&) const 和 bool operator<(const mask&, const mask&) 编译器就会报错
自定义类型mask
提供 operator <, std::less 的默认实现
struct mask {
string str;
bool operator < (const mask &r) const {
return str < r.str;
}
};
特化std::less<mask>
namespace std {
template <>
struct less<mask> {
bool operator () (const mask &l, const mask &r) {
return l.str < r.str;
}
};
}
std::less 默认实现
bool operator < (const mask &l, const mask &r) {
return l.str < r.str;
}
初始化set<mast> 指定 compare : set<mask, mask_less>
struct mask_less : public std::binary_function <mask, mask, bool> {
bool operator () (const mask &l, const mask &r) const {
return l.str < r.str;
}
};
/usr/include/c++/4.7/bits/stl_function.h:237:22: error: ambiguous overload for ‘operator<’ in ‘__x < __y’
/usr/include/c++/4.7/bits/stl_function.h:237:22: note: candidates are:
test_set.cpp:9:8: note: bool mask::operator<(const mask&) const
test_set.cpp:23:6: note: bool operator<(const mask&, const mask&)
unordered_set & mask
unordered_set 和 std::hash, std::equal_to 的原型
template<
class Key,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<Key>
> class unordered_set;
template<typename _Tp>struct std::hash< _Tp >
template<typename _Tp>
struct hash : public __hash_base<size_t, _Tp>
{
static_assert(sizeof(_Tp) < 0,
"std::hash is not specialized for this type");
size_t operator()(const _Tp&) const noexcept;
};
template<typename _Tp>struct std::equal_to< _Tp >
template<typename _Tp>
struct equal_to : public binary_function<_Tp, _Tp, bool>
{
bool operator()(const _Tp& __x, const _Tp& __y) const
{ return __x == __y; }
};
unordered_set 和mask 类一起使用, mask 类型 需要提供std::hash<mask> , std::equal_to<mask>.
struct mask {
string str;
size_t hash_value () const {
return boost::hash_range (str.begin (), str.end ());
}
};
namespace std {
template <>
struct hash<mask> {
size_t operator () (const mask &m) const {
return boost::hash_range (str.begin (), str.end ());
}
};
template <>
struct equal_to<mask> : public binary_function<mask, mask, bool> {
bool operator () (const mask &l, const mask &r) const {
return l.hash_value () == r.hash_value ();
}
};
}
boost 对C++内置的类型 (int, char 等) 的 hash 默认支持。 借用boost::hasn_range<char> 实现mask 的hash计算