调用map的insert函数的问题

pzp 2006-12-07 11:46:35
我调试发现,如果map中当前key已经存在,再调用insert(key,newvalue)插入不会成功,不知道为什么不会覆盖.
...全文
1291 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
OOPhaisky 2006-12-07
  • 打赏
  • 举报
回复
用operator[]就可以“覆盖”了。
lann64 2006-12-07
  • 打赏
  • 举报
回复
下标操作在找不到key时调用insert是可能的,但找到了就执行赋值操作了,跟insert不是一回事。
taodm 2006-12-07
  • 打赏
  • 举报
回复
“我看书上说这样作也仍旧是调用insert函数的”
是哪本书?
错了!
pzp 2006-12-07
  • 打赏
  • 举报
回复
那为什么map[key]=newvalue却能成功,我看书上说这样作也仍旧是调用insert函数的.
lann64 2006-12-07
  • 打赏
  • 举报
回复
STL里map就是这样实现的。没有为什么。
m.insert(e) e is a value of the value_type from m. If the key (e.first)is not in m,insert a new element with value e.second. If the key is in m,then m is unchanged.
Returns a pair containing a map iterator referring to the element with key e.first and a bool indicating whether the element was inserted or not.
lovesnow1314 2006-12-07
  • 打赏
  • 举报
回复
The first insert member function returns a pair whose bool component returns true if an insertion was made and false if the map already contained an element whose key had an equivalent value in the ordering, and whose iterator component returns the address where a new element was inserted or where the element was already located.

To access the iterator component of a pair pr returned by this member function, use pr.first, and to dereference it, use *(pr.first). To access the bool component of a pair pr returned by this member function, use pr.second.

The second insert member function, the hint version, returns an iterator that points to the position where the new element was inserted into the map.
missilery 2006-12-07
  • 打赏
  • 举报
回复
insert
Syntax:
#include <map>
iterator insert( iterator i, const TYPE& pair );
void insert( input_iterator start, input_iterator end );
pair<iterator,bool> insert( const TYPE& pair );
The function insert() either:
● inserts pair after the element at pos (where pos is really just a suggestion as to where pair
should go, since sets and maps are ordered), and returns an iterator to that element.
● inserts a range of elements from start to end.
--------------
● inserts pair, but only if pair doesn't already exist. The return value is an iterator to the element
inserted, and a boolean describing whether an insertion took place.
HappyTree 2006-12-07
  • 打赏
  • 举报
回复
insert(key,newvalue)
是否可以这么理解:
如果key存在的话,返回值为false,那么如果你把值替换了的话,这个false如何解释呢?
如果不管如何,都显示插入成功,这样你原先的值就被覆盖了,而你甚至不知道何时被替换,这样的接口设计是有缺陷的。
至于map[key]=newvalue,我觉得主要原因在于这里是赋值操作,没有办法提示你key的存在,所以直接覆盖是合理的。但STL的书籍上一般都会告诉读者尽量不要这么用。

64,637

社区成员

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

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