繁体   English   中英

在C ++中插入以映射类型

[英]insertion to type map in c++

我不明白那段代码是做什么的

static TwoWayHostPair hostpair;
map <TwoWayHostPair, Traffic> mymap;
//here some map element inserted to mymap and hostpair initialized

map <TwoWayHostPair, Traffic>::iterator iter = mymap.begin();
iter = mymap.find(hostpair);
if (iter == mymap.end()) { 
    iter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8
}

我的问题是第8行会发生什么? 我没明白。 它不是应该为map<...>:iterator类型,插入之后是否保持相同类型?

std :: map :: insert返回std :: pair <迭代器,布尔> ,下面的语句是正确的。 第二个布尔返回值指示插入是否发生

iter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8

在这里看到参考

在这里使用

iter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8

mymap.insert 返回 pair<iterator,bool> first ,然后访问 iterator

insert(make_pair......

make_pair用于将对值插入到映射中。您已对映射中具有主机对的所有元素进行了迭代。

编辑请参阅cplusplus地图以了解更多信息。

iter = mymap.find(hostpair);
if (iter == mymap.end()) { 
    iter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8
}

第一行在映射中查找hostPair ,如果未找到键,则进入if块,在其中插入键及其值,然后.first将迭代器返回到插入的项。


起色

但是您可以对此进行改进。 您可以这样写:

iter = mymap.insert(make_pair(hostPair, Traffic())).first; 

这完全等同于您的代码。 无需使用find然后insert 结果是提高了性能

如果键已经存在,则insert函数将不会在地图上插入任何项目,并且.first将使迭代器返回到找到的项目。 如果键不存在,则只有键会插入, .first将使迭代器返回到新插入的项。

如果您想知道密钥是否已经存在,则可以执行以下操作:

auto pair = mymap.insert(make_pair(hostPair, Traffic())); //NO .first!
if (pair.second)
{
     //a newly created item is inserted 
     auto iter = pair.first; //iterator to the newly inserted item
}
else
{
    //an item with key `hostPair` already exists in the map
     auto iter = pair.first; //iterator to the found item
}

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM