C ++ STL映射

系统教程 行业动态 更新时间:2024-06-14 17:03:54
C ++ STL映射 - 条件插入(C++ STL map - conditional insert)

我正在寻找一种有效的方式来执行条件插入。 理想情况下,我想要一个可以在任何地图上工作的模板函数。 我想要这样的东西:

std::map<int, std::string> MyMap; if(MyMap.ConditionalInsert(3, "Hello")) { // there was no element 3, one has been added with value "Hello" } else { // there was already an element 3 in the map, it's unchanged }

我不能轻易使用operator[]因为没有简单的方法来判断它是否创建了一个元素。 我可以使用count来进行测试,但是如果我们插入数据,则必须重新搜索地图两次。 我猜想find东西最好,但它似乎总是出现w and和尴尬。

有没有一个很好的方法来做到这一点?

I'm looking for an efficient way to do a conditional insert. Ideally, I'd like a template function that would work on any map. I want something like this:

std::map<int, std::string> MyMap; if(MyMap.ConditionalInsert(3, "Hello")) { // there was no element 3, one has been added with value "Hello" } else { // there was already an element 3 in the map, it's unchanged }

I can't easily use operator[] because there's no easy way to tell if it created an element or not. I can use count for the test, but then I have to search the map twice if we do an insert. I guess something with find would be best, but it always seems to come out warty and awkward.

Is there a really good way to do this?

更多推荐

本文发布于:2023-04-24 14:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/d7b87ff511cd37487c6ab5b01da18af8.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:STL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!