如果我计划使用任意类对象作为键,我可以使用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.