如果我计划使用任意类对象作为键,我可以使用stl地图吗? [英] Can I use an stl map if I plan to use arbitrary class objects as the key?

查看:104
本文介绍了如果我计划使用任意类对象作为键,我可以使用stl地图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触STL。关于使用地图存储任意对象的事情:

I'm new to STL. The thing stumping me about using a map to store arbitrary objects:

std::map<MyClassObj, MyDataObject> MyMap;

是我如何查找对象。 MyMap.find(MyClassObjInstance)如何工作实例?我需要实现我自己的迭代器,并提供一些标准函数,其中包括一些等价函数?

is how I find objects. How would MyMap.find (MyClassObjInstance) work for instance? Do I need to implement my own iterator and provide some standard functions which would include some equivalence function? Any examples would be appreciated.

是否有另一种方法使用标准库来存储任意对象的关联列表?我已经使用stl来维护平台的可移植性,并且不喜欢添加另一个库依赖关系像BOOST。

Is there another method to store an associated list of arbitrary objects using standard libraries? I'm already using stl to maintain platform portability, and would prefer not to add another library dependency like BOOST.

推荐答案

std :: map 有一个第三个模板参数,在键和值之后,表示要用来比较键的函数。默认情况下,它是 std :: less ,它依次使用运算符< 。所以如果你的类有一个运算符<,它没关系,否则你可以提供一个自己的比较器。

std::map has a third template argument, after key and value, to denote what function is going to be used to compare keys. By default, it is std::less, which in it's turn uses operator<. So if your class has an operator<, it's ok, else you can provide a comparator of your own.

这篇关于如果我计划使用任意类对象作为键,我可以使用stl地图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆