您的位置:首页 > 其它

使用用户自定义类型作为map的key

2015-06-03 10:44 429 查看
有时候我们想把用户自定义类型作为std::map的键值。
方法一)最简单的方法就是实现该自定义类型的<操作符,代码如下:
class Foo
{
public:
Foo(int num_)
: num(num_)
{
}
bool operator < (const Foo & cmp) const
{
return num < cmp.num;
}
int num;
};
之后就可以使用Foo作为map的key了:
map<Foo, int> dict; // 该句等同于map<Foo, int, std::less<Foo> > dict;
dict[Foo(1)] = 1;
不过有时候,这招不好使,比如对下面的Foo2:
typedef std::pair<Foo, int> Foo2;
方法二)定义一个比较操作符,使用它作为map的模板参数,代码如下:
class Foo2Comparator
{
public:
bool operator()(const Foo2& key1, const Foo2& key2) const
{
if (key1.first < key2.first)
{
return true;
}
else if (key2.first < key1.first)
{
return false;
}
else
{
return key1.second < key2.second;
}
}
};
这时候可以使用Foo2作为map的key了:
map<Foo2, int, Foo2Comparator> dict2;
dict2[Foo2(Foo(1), 100)] = 1;
方法三)为用户自定义类型特化std::less,代码如下:
namespace std
{
template <>
struct less<Foo2>
: public binary_function <Foo2, Foo2, bool>
{
bool operator()(const Foo2& key1, const Foo2& key2) const
{
if (key1.first < key2.first)
{
return true;
}
else if (key2.first < key1.first)
{
return false;
}
else
{
return key1.second < key2.second;
}
}
};
}
使用这种方法,声明map时无需指定比较函数对象,因为默认的比较对象就是std::less<T>,
map<Foo2, int> dict2;
dict2[Foo2(Foo(1), 100)] = 3;
======================================================
三种方法里面我最喜欢第二种,虽然使用起来略微复杂(多了一个模板参数),但最为明确清晰。
另外如果使用std::pair<T1, T2>作为map的key,若T1、T2是原始类型,那么使用默认的std::less<std::pair<T1, T2> >一般就ok了,没啥必要去自己折腾。
typedef std::pair<double, int> Pos;
std::map<Pos, int> dict3;
dict3[Pos(1.1, 10)] = 100;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: