如何确保 std::map 是有序的? [英] How to ensure that a std::map is ordered?

查看:106
本文介绍了如何确保 std::map 是有序的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 std::map<int, ...> 如何确保在插入时迭代将按整数键的升序进行?

Using a std::map<int, ...> how can I ensure at inserting time that iterating over it will take place in ascending order of the integer key?

推荐答案

您无需执行任何操作.地图将根据键的值按升序排列.

You don't have to do anything. The map will be in ascending order according to the values of the key.

在内部,映射执行键之间的比较以对其元素进行排序.默认情况下,它使用 std::less,这相当于整数的 bool operator<(int, int).对于用户定义的类型,您必须选择:

Internally, the map performs a comparison between keys to order its elements. By default, it uses std::less<KEY>, which is equivalent to bool operator<(int, int) for integers. For user defined types, you have to options:

  1. 实施一个 bool 运算符<(const MyType&, const MyType&),在您的用户定义的类型之间实施严格的弱排序比较.如果您的类型具有自然顺序,请使用此选项

  1. Implement a bool operator<(const MyType&, const MyType&) implementing a strict weak ordering comparison between your user defined types. Use this if your type has a natural ordering

提供一个实现严格弱排序的二元函子,您可以将其作为第三个模板参数传递给地图.如果您的类型没有自然排序,或者如果您想使用与 std::less 通过 bool 运算符<使用的排序不同的排序来构建映射,请使用此选项.(...) 从第 1 点开始.

Provide a binary functor that implements strict weak ordering, which you can pass as the 3rd template parameter to the map. Use this if your type does not have a natural ordering, or if you want to build the map with an ordering different to that used by std::less<Key> via the bool operator<(...) from point 1.

通常在幕后发生的是,映射被实现为自平衡二叉树,并且使用严格弱排序在映射中放置新元素,并确定两个元素是否相等.顺便说一句,相同的逻辑适用于 std::set,其中键和值是一且相同的.

What typically happens behind the scenes is that the map is implemented as a self-balancing binary tree, and the strict weak ordering is used to place new elements in the map, and to determine whether two elements are equal. As an aside, the same logic applies to std::set, where the key and value are one and the same.

这篇关于如何确保 std::map 是有序的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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