是通过std :: map的迭代顺序已知(并且由标准保证)? [英] Is the order of iterating through std::map known (and guaranteed by the standard)?

查看:147
本文介绍了是通过std :: map的迭代顺序已知(并且由标准保证)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是 - 我们知道 std :: map 的元素根据键排序。所以,让我们说键是整数。如果我从 std :: map :: begin() std :: map :: end() a for ,标准保证,我将迭代,因此通过键的元素,按升序排序?

What I mean is - we know that the std::map's elements are sorted according to the keys. So, let's say the keys are integers. If I iterate from std::map::begin() to std::map::end() using a for, does the standard guarantee that I'll iterate consequently through the elements with keys, sorted in ascending order?

例如:

std::map<int, int> map_;
map_[1] = 2;
map_[2] = 3;
map_[3] = 4;
for( std::map<int, int>::iterator iter = map_.begin();
     iter != map_.end();
     ++iter )
{
    std::cout << iter->second;
}

这样可以保证打印 234

现实生活理由:我有一个 std: :map int 键。在非常罕见的情况下,我想遍历所有的元素,用键,大于一个具体的 int 值。是的,它听起来像 std :: vector 将是更好的选择,但注意我的非常罕见的情况。

Real life reason: I have a std::map with int keys. In very rare situations, I'd like to iterate through all elements, with key, greater than a concrete int value. Yep, it sounds like std::vector would be the better choice, but notice my "very rare situations".

EDIT :我知道 std :: map 的元素被排序。没有必要指出它(大多数的答案在这里)。我甚至在我的问题中写了。

我在询问迭代器和迭代容器时的顺序。感谢@Kerrek SB的回答。

EDIT: I know, that the elements of std::map are sorted.. no need to point it out (for most of the answers here). I even wrote it in my question.
I was asking about the iterators and the order when I'm iterating through a container. Thanks @Kerrek SB for the answer.

推荐答案

是的,这是保证。此外, * begin()给出最小值, * rbegin()运算符,以及表达式!compare(a,b)的两个键值 a b b)&& !compare(b,a)为true被认为是相等的。默认的比较函数是 std :: less< K>

Yes, that's guaranteed. Moreover, *begin() gives you the smallest and *rbegin() the largest element, as determined by the comparison operator, and two key values a and b for which the expression !compare(a,b) && !compare(b,a) is true are considered equal. The default comparison function is std::less<K>.

顺序不是幸运奖金功能,而是它是数据结构的基本方面,因为排序用于确定何时两个密钥相同(通过上述规则)并且执行有效的查找(本质上是二进制搜索,其在数量上具有对数复杂性的元素)。

The ordering is not a lucky bonus feature, but rather, it is a fundamental aspect of the data structure, as the ordering is used to determine when two keys are the same (by the above rule) and to perform efficient lookup (essentially a binary search, which has logarithmic complexity in the number of elements).

这篇关于是通过std :: map的迭代顺序已知(并且由标准保证)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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