std ::索引和插入调用之间的映射差异 [英] std::map difference between index and insert calls

查看:128
本文介绍了std ::索引和插入调用之间的映射差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



ie:

  some_map [x] = 500; 

vs。

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


解决方案

我相信insert()不会覆盖现有值,并且可以通过测试所返回的迭代器/对值中的bool值来检查操作的结果



对下标运算符[]的赋值仅覆盖其中的任何值插入一个条目,如果没有已经有一个条目)



插入和[]操作符可能会导致问题,如果你没有期望的行为,

  std :: 

地图< 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)); //失败,s2不在map中,如果不整理就可能泄漏

  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现在从地图上删除,如果不整理就可能泄漏

,但尚未编译它们,因此可能会出现语法错误


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

ie:

some_map["x"] = 500;

vs.

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

解决方案

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.

Eg with insert:

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 [] 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 ::索引和插入调用之间的映射差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆