索引和插入调用之间的 std::map 区别

std::map difference between index and insert calls(索引和插入调用之间的 std::map 区别)
本文介绍了索引和插入调用之间的 std::map 区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

索引重载运算符和std::map的insert方法调用有什么区别?

What is the difference between the index overloaded operator and the insert method call for std::map?

即:

some_map["x"] = 500;

对比

some_map.insert(pair<std::string, int>("x", 500));

推荐答案

相信insert()不会覆盖已经存在的值,可以通过测试返回的iterator/pair值中的bool值来检查操作结果

I believe insert() will not overwrite an existing value, and the result of the operation can be checked by testing the bool value in the iterator/pair value returned

对下标运算符 [] 的赋值只会覆盖那里的任何内容(如果那里还没有,则插入一个条目)

The assignment to the subscript operator [] just overwrites whatever's there (inserting an entry if there isn't one there already)

如果您没有预料到这种行为并且不适应这种行为,那么插入和 [] 运算符中的任何一个都可能导致问题.

Either of the insert and [] operators can cause issues if you're not expecting that behaviour and don't accommodate for it.

例如插入:

std::map< int, std::string* > intMap;
std::string* s1 = new std::string;
std::string* s2 = new std::string;
intMap.insert( std::make_pair( 100, s1 ) ); // inserted
intMap.insert( std::make_pair( 100, s2 ) ); // fails, s2 not in map, could leak if not tidied up

and with [] 运算符:

and with [] operator:

std::map< int, std::string* > intMap;
std::string* s1 = new std::string;
std::string* s2 = new std::string;
intMap[ 100 ] = s1; // inserted
intMap[ 100 ] = s2; // inserted, s1 now dropped from map, could leak if not tidied up

我认为这些是正确的,但没有编译它们,所以可能有语法错误

I think those are correct, but haven't compiled them, so may have syntax errors

这篇关于索引和插入调用之间的 std::map 区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)