foreach在地图上的意外副本 [英] unexpected copies with foreach over a map
本文介绍了foreach在地图上的意外副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图循环地图的条目,我得到意外的副本。这是程序:
#include< iostream>
#include< map>
#include< string>
struct X
{
X()
{
std :: cout< default constructor\\\
;
}
X(const X&)
{
std :: cout< copy constructor\ n;
}
};
int main()
{
std :: map< int,X>数字= {{1,X()},{2,X()},{3,X()}}
std :: cout<< STARTING LOOP\\\
;
for(const std :: pair< int,X>& p:numbers)
{
}
std :: cout< ENDING LOOP\\\
;
}
这里是输出:
默认构造函数
复制构造函数
默认构造函数
复制构造函数
默认构造函数
复制构造函数
复制构造函数
复制构造函数
复制构造函数
启动循环
复制构造函数
复制构造函数
复制构造函数
ENDING LOOP
为什么我在循环中得到三个副本?如果我使用类型推断,则副本会消失:
for(auto& p:numbers)
{
}
map< K,V>
的值类型是 pair< const K,V& / code>;因此你的循环需要将 pair< const int,X>
转换为 pair< int,X>
使用正确的类型(明确指定或推导出 auto
)将删除副本。
I am trying to loop over the entries of a map, and I get unexpected copies. Here is the program:
#include <iostream>
#include <map>
#include <string>
struct X
{
X()
{
std::cout << "default constructor\n";
}
X(const X&)
{
std::cout << "copy constructor\n";
}
};
int main()
{
std::map<int, X> numbers = {{1, X()}, {2, X()}, {3, X()}};
std::cout << "STARTING LOOP\n";
for (const std::pair<int, X>& p : numbers)
{
}
std::cout << "ENDING LOOP\n";
}
And here is the output:
default constructor
copy constructor
default constructor
copy constructor
default constructor
copy constructor
copy constructor
copy constructor
copy constructor
STARTING LOOP
copy constructor
copy constructor
copy constructor
ENDING LOOP
Why do I get three copies inside the loop? The copies disappear if I use type inference:
for (auto&& p : numbers)
{
}
What's going on here?
解决方案 The value type of map<K,V>
is pair<const K,V>
; so your loop needs to convert pair<const int,X>
to pair<int,X>
, copying both the key and the value, to give you a reference to that type.
Using the correct type (specified explicitly, or deduced with auto
) will remove the copies.
这篇关于foreach在地图上的意外副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文