如果我打算使用任意类对象作为键,我可以使用 stl 映射吗?
我是STL新手。使用地图来存储任意对象让我感到困惑的是:
std::map<MyClassObj, MyDataObject> MyMap;
我如何找到对象。例如,MyMap.find (MyClassObjInstance) 如何工作?我是否需要实现自己的迭代器并提供一些标准函数(其中包括一些等价函数)?任何例子将不胜感激。
是否有另一种方法可以使用标准库存储任意对象的关联列表?我已经在使用 stl 来维护平台的可移植性,并且不希望添加另一个库依赖项,例如 BOOST。
I'm new to STL. The thing stumping me about using a map to store arbitrary objects:
std::map<MyClassObj, MyDataObject> MyMap;
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
std::map 在键和值之后有第三个模板参数,用于指示将使用哪个函数来比较键。默认情况下,它是
std::less
,它又使用operator<
。因此,如果您的类有一个运算符<,那就没问题,否则您可以提供自己的比较器。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 isstd::less
, which in it's turn usesoperator<
. So if your class has an operator<, it's ok, else you can provide a comparator of your own.您只需为
MyClassObj
定义operator<
即可。有关 std::map 的更多信息,您可以阅读此处。根据 C++ 标准 23.1.2:
默认情况下,
comp
为std::less
。根据 C++ 标准 20.3.3:
当然,您可以定义独立函子
comp
进行比较。All of you need is to define
operator<
forMyClassObj
. For more information about std::map you could read here.According to C++ Standard 23.1.2:
By default
comp
isstd::less
.According to C++ Standard 20.3.3:
Surely, you could define stand alone functor
comp
for comparison.map 的完整类型是
它默认使用 less,但只要你传入一个重载了operator()的类来获取对象的两个实例并返回一个bool,一切都很好。请注意,如果您给它 comp(a,b) 并且它返回 true,那么 a 在排序中应该位于 b 之前。
The full type for map is
It uses less than by default but as long as you pass in a class that has operator () overloaded to take two instances of the object and returns a bool all is well. note if you give it comp(a,b) and it returns true, then a should come before b in the ordering.
是的,您可以使用自己的类型/对象作为键。他们必须实现小于运算符 (operator<),因为所有有序标准 C++ 容器都使用此运算符来测试排序和相等性。
Yes, you can use your own type/object as a key. They'll have to implement the less-than operator (operator<) as all ordered standard C++ containers do use this operator to test for ordering and equality.