[英]Why does std::map::const_iterator call the std::pair constructor during a std::for_each, but a simple for loop does not?
I have a slightly complex data member of a class, as noted in what follows: 我有一个稍微复杂的类数据成员,如下所示:
class BranchOutputRow
{
...
}
class Foo
{
public:
// Slightly complex data member here
std::map<boost::multiprecision::cpp_int, std::set<BranchOutputRow>> hits;
void DoLoop1()
{
// This loop calls the std::pair<> constructor
std::for_each(hits.cbegin(), hits.cend(),
[&](std::pair<boost::multiprecision::cpp_int,
std::set<BranchOutputRow>> const & hit)
{
...
}
}
void DoLoop2()
{
// This loop does NOT call the std::pair<> constructor
for (std::map<boost::multiprecision::cpp_int,
std::set<BranchOutputRow>>::const_iterator hitsPtr
= hits.cbegin();
hitsPtr != hits.cend();
++hitsPtr)
{
...
}
}
}
int main()
{
Foo foo;
foo.hits[1] = std::set<BranchOutputRow>();
foo.hits[1].insert(BranchOutputRow());
foo.DoLoop1(); // direct access to map object is not available
foo.DoLoop2(); // direct access to map object is available
}
As noted, I find that Loop #1 calls the std::pair
constructor, despite the fact that the lambda function accepts its argument by reference. 如上所述,我发现Loop#1调用
std::pair
构造函数,尽管lambda函数通过引用接受其参数。 Therefore, in Loop 1, I do not have direct access to the object in the map, but only a copy. 因此,在循环1中,我没有直接访问地图中的对象,而只是副本。 In my actual program, I need direct access;
在我的实际计划中,我需要直接访问; therefore, I must use the version indicated by Loop 2.
因此,我必须使用循环2指示的版本。
(In fact, Loop 2 does not call the std::pair
constructor - not a surprise - and does provide direct access to the object in the map.) (事实上,环2 不调用
std::pair
构造-不是一个惊喜-并没有提供对地图对象的直接访问。)
I would think that std::for_each
would have been carefully designed to provide the same semantics as a for
loop such as Loop 2, and therefore not call the std::pair
constructor, instead allowing direct access to the object in the map. 我认为
std::for_each
会经过精心设计,提供与for
循环相同的语义,例如Loop 2,因此不会调用std::pair
构造函数,而是允许直接访问map中的对象。
Why does Loop 1 call the std::pair
constructor, despite the fact that the lambda function accepts its argument by reference? 为什么Loop 1调用
std::pair
构造函数,尽管lambda函数通过引用接受它的参数?
The value_type
of std::map<K,V>
is std::pair<const K, V>
. std::map<K,V>
的value_type
是std::pair<const K, V>
。 Your lambda takes std::pair<K,V>
. 你的lambda采用
std::pair<K,V>
。 Note the difference in constness. 注意constness的差异。
The conversion is done through this constructor: 转换是通过以下构造函数完成的:
template< class U1, class U2 >
pair( const pair<U1, U2>& p );
(see (4) on this reference page ) (参见本参考页面上的(4))
The result of the conversion is a temporary, and temporaries can bind to const references, so your code works. 转换的结果是临时的,临时文件可以绑定到const引用,因此您的代码可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.