map中遍历迭代器为何是按照键从小到大遍历的

zjtzlqr 2015-01-11 11:58:48
#include <map>
#include <iostream>

int main( )
{
using namespace std;
map <int, int> m1;

map <int, int> :: iterator m1_Iter;
map <int, int> :: const_iterator m1_cIter;
typedef pair <int, int> Int_Pair;

m1.insert ( Int_Pair ( 1, 1 ) );
m1.insert ( Int_Pair ( 2, 2 ) );
m1.insert ( Int_Pair ( 3, 3 ) );
m1.insert ( Int_Pair ( 5, 5) );
m1.insert ( Int_Pair ( 11, 11 ) );
m1.insert ( Int_Pair ( 4, 4 ) );

m1_cIter = m1.begin ( );

for (;m1.end() != m1_cIter; m1_cIter++)
{
cout << "The first element of m1 is " << m1_cIter -> first << endl;

}


}


map中遍历迭代器为何是按照键从小到大遍历的


红黑树是每个节点都带有颜色属性的二叉查找树,颜色或红色或黑色。在二叉查找树强制一般要求以外,对于任何有效的红黑树我们增加了如下的额外要求:
性质1. 节点是红色或黑色。
性质2. 根节点是黑色。
性质3 每个叶节点(NIL节点,空节点)是黑色的。
性质4 每个红色节点的两个子节点都是黑色。(从每个叶子到根的所有路径上不能有两个连续的红色节点)
性质5. 从任一节点到其每个叶子的所有路径都包含相同数目的黑色节点。
...全文
950 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
fefe82 2015-12-04
  • 打赏
  • 举报
回复
引用 10 楼 github_33254900 的回复:
但是用enumeration遍历hashtable是从大往小遍历的
C++ 标准没有提供 hashtable ,只有 unordered_map 和 unordered_set 。这两个,就像名字所说的,是无序的。
Yixiong_Cao 2015-12-04
  • 打赏
  • 举报
回复
但是用enumeration遍历hashtable是从大往小遍历的
Evankaka 版主 2015-01-12
  • 打赏
  • 举报
回复
因为程序是这么设计的。它反正是有序的
luciferisnotsatan 2015-01-12
  • 打赏
  • 举报
回复
引用 4 楼 luciferisnotsatan 的回复:
lz的问题帖里已经说了红黑树了,那么lz应该知道为何是有序的了吧。 至于为何从小到大,而不是从大到小,那是因为模板默认用了less<Key>来比较。你当然也可以自己给个Traits来从大到小排(STL里已经有 great<Key> 这个算法了),或者自定义一个 template < class Key, class Type, class Traits = less<Key>, class Allocator=allocator<pair <const Key, Type> > > class map;
迭代器中序遍历红黑树,就是从小到大遍历的。如果lz问得是迭代器如何来从小到大,一个个遍历的话
starytx 2015-01-12
  • 打赏
  • 举报
回复
map就是自动排序的,为了快速检索,要不然你就用vector
u010231493 2015-01-12
  • 打赏
  • 举报
回复
map会自动排序。按照jian值排序。你可以百度,map修改排序。
  • 打赏
  • 举报
回复
要改变排序方式,重载运算符
xiaohuh421 2015-01-12
  • 打赏
  • 举报
回复
map会自动改变数据插入位置
luciferisnotsatan 2015-01-12
  • 打赏
  • 举报
回复
lz的问题帖里已经说了红黑树了,那么lz应该知道为何是有序的了吧。 至于为何从小到大,而不是从大到小,那是因为模板默认用了less<Key>来比较。你当然也可以自己给个Traits来从大到小排(STL里已经有 great<Key> 这个算法了),或者自定义一个 template < class Key, class Type, class Traits = less<Key>, class Allocator=allocator<pair <const Key, Type> > > class map;
ri_aje 2015-01-12
  • 打赏
  • 举报
回复
传说中的规定,标准要求 map 里的元素是已序的,并且迭代器按照顺序遍历。 ps. 标准没说 std::map 要用红黑树实现,也没说一定要用 bst 实现。
zjtzlqr 2015-01-11
  • 打赏
  • 举报
回复
The first element of m1 is 1 The first element of m1 is 2 The first element of m1 is 3 The first element of m1 is 4 The first element of m1 is 5 The first element of m1 is 11 请按任意键继续. . .

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧