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?
更多推荐
发布评论