对map迭代器有些不理解,大侠们看看!

8毛_ 2012-01-21 07:46:46
假设定义一个map容器,其iter为map容器的迭代器!
要对其map容器的元素复制时,为什么是 iter->second=val,而不是(*iter)->second=val.
(val为要赋给元素的值)!



疑惑:不是对iter解引用才获得一个pair,然后再对pair->second吗?
大侠们看看!
...全文
221 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2012-01-22
  • 打赏
  • 举报
回复
因为*iter调用iter.operator*,其返回值是pair<x,y>&,而iter->调用iter.operator->,返回是pair<x,y>*,这就是关系...
轩辕魂 2012-01-22
  • 打赏
  • 举报
回复
->操作符被map迭代器重载了
0xAC 2012-01-21
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 mingliang1212 的回复:]

it->与(*it). 是一个语义的。
[/Quote]
正解!
pathuang68 2012-01-21
  • 打赏
  • 举报
回复
权威资料是这么说的:
Iterators of a map container point to elements of this value_type. Thus, for an iterator called it that points to an element of a map, its key and mapped value can be accessed respectively with:

map<Key,T>::iterator it;
(*it).first; // the key value (of type Key)
(*it).second; // the mapped value (of type T)
(*it); // the "element value" (of type pair<const Key,T>)


Naturally, any other direct access operator, such as -> or [] can be used, for example:

it->first; // same as (*it).first (the key value)
it->second; // same as (*it).second (the mapped value)


楼主可以自己去http://www.cplusplus.com/reference/stl/map/看看,玩C++的人,这个网站通常是要经常光顾的。
Fergon 2012-01-21
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 rdy2012 的回复:]

可是书上就是iter->second,而不是(*iter)->second!
why?
[/Quote]
为什么是(*iter) -> second ??

(*iter) .second 才有可能。

iter就相当于一个指针,我很奇怪你为什么会有这种想法?
8毛_ 2012-01-21
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 mingliang1212 的回复:]

it->与(*it). 是一个语义的。
[/Quote]
饿,是这样的啊!
iamnobody 2012-01-21
  • 打赏
  • 举报
回复
it->与(*it). 是一个语义的。
8毛_ 2012-01-21
  • 打赏
  • 举报
回复
可是书上就是iter->second,而不是(*iter)->second!
why?
zhangsongcui 2012-01-21
  • 打赏
  • 举报
回复
对iter解引用才获得一个pair
然后再对pair.second

64,636

社区成员

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

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