unordered_map::find() 插入查找的键
unordered_map::find() 的一个功能是自动插入我们查找的值为 0 的键吗? 让我说清楚
unordered_map<int, int> tempMap;
//some code
if(tempMap.find(1) == tempMap.end()){
//do something but not insert the 1 with a corresponding value into the tempMap
}
,如果我再次查找 1,它在 tempMap 中是否会有 0 作为对应值。 这是unordered_map的一个特性吗?
Is it a feature of unordered_map::find() to insert the key that we lookup with 0 value automatically?
Let me make this clear
unordered_map<int, int> tempMap;
//some code
if(tempMap.find(1) == tempMap.end()){
//do something but not insert the 1 with a corresponding value into the tempMap
}
so if I lookup 1 again, will it be there in the tempMap having 0 as corresponding value.
Is that a feature of unordered_map?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,
find
仅搜索并返回迭代器。也就是说,
std::unordered_map
(和std::map
)都会重载将插入的operator[]
如果需要,可以使用默认值:No,
find
only searches and returns an iterator.That said,
std::unordered_map
(andstd::map
) both overloadoperator[]
which will insert a default if needed:否 -
find
不插入值。如果您想要插入之前不存在的值,则可以使用
operator[]
而不是find
。这样做是因为
operator[]
返回对对象的引用。由于不存在空引用之类的东西,因此本质上唯一的选择是让它在搜索以前不存在的项目时抛出异常。已经有一些容器采用了这种行为,但它显然不是很有用,而且从未获得太多的欢迎(我使用了一些这样的容器,发现它很痛苦)。No --
find
does not insert values.If you want to insert the value if it was not previously present, then you can use
operator[]
instead offind
.This is done because
operator[]
returns a reference to an object. Since there's no such thing as a null reference, essentially the only alternative would be to have it throw an exception when searching for an item that wasn't previously present. There have been some containers that adopted that behavior, but it wasn't apparently very useful and never gained much popularity (I used some containers like that and found it a pain).