C++ 插入到c+中的类型映射+;
我不明白那段代码是做什么的C++ 插入到c+中的类型映射+;,c++,map,iterator,C++,Map,Iterator,我不明白那段代码是做什么的 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(hostpai
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
}
静态双向主机对;
地图我的地图;
//这里插入了一些映射元素到mymap并初始化了hostpair
迭代器iter=mymap.begin();
iter=mymap.find(主机对);
如果(iter==mymap.end()){
iter=mymap.insert(make_pair(hostPair,Traffic())。首先;//第8行
}
我的问题是第8行发生了什么?我不明白。它不是应该是类型
map:iterator
吗?在插入之后,它是否保持相同的类型?std::map::insert returnstd::pairiter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8
请参阅参考std::map::insert returnstd::pair
iter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8
参见此处使用的参考资料
iter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8
mymap.插入apair
首先
,然后是此处使用的迭代器
iter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8
insert(make_pair......
mymap.插入apair
首先
,然后是迭代器
insert(make_pair......
make_pair
用于向映射插入对值。您已对映射中具有hostpair的所有元素进行了迭代
编辑
参考了解更多
iter = mymap.find(hostpair);
if (iter == mymap.end()) {
iter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8
}
make_pair
用于向映射插入对值。您已对映射中具有hostpair的所有元素进行了迭代
编辑
参考了解更多
iter = mymap.find(hostpair);
if (iter == mymap.end()) {
iter = mymap.insert(make_pair(hostPair, Traffic())).first; //line8
}
第一行在映射中查找键hostPair
,如果找不到,则进入if
块,插入键及其值,然后。第一行将迭代器返回到插入的项
改进
但你可以对此进行改进。你可以这样写:
iter = mymap.insert(make_pair(hostPair, Traffic())).first;
这与您的代码完全等价。无需使用查找
,然后使用插入
。结果是性能提高
如果键已经存在,则insert
函数将不会向映射中插入任何项,并且会首先将迭代器返回到找到的项。如果该键不存在,则只会插入,然后。首先会将迭代器返回给新插入的项
如果您想知道密钥是否已经存在,则可以执行以下操作:
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
}
希望有帮助
第一行在映射中查找键hostPair
,如果找不到,则进入if
块,插入键及其值,然后。第一行将迭代器返回到插入的项
改进
但你可以对此进行改进。你可以这样写:
iter = mymap.insert(make_pair(hostPair, Traffic())).first;
这与您的代码完全等价。无需使用查找
,然后使用插入
。结果是性能提高
如果键已经存在,则insert
函数将不会向映射中插入任何项,并且会首先将迭代器返回到找到的项。如果该键不存在,则只会插入,然后。首先会将迭代器返回给新插入的项
如果您想知道密钥是否已经存在,则可以执行以下操作:
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
}
希望能有所帮助。这一部分很明显,我问的问题下面由内特·钱德勒和比尔茨回答。这一部分很明显,我问的问题下面由内特·钱德勒和比尔茨回答