[英]Why does std::map::const_iterator call the std::pair constructor during a std::for_each, but a simple for loop does not?
我有一個稍微復雜的類數據成員,如下所示:
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
}
如上所述,我發現Loop#1調用std::pair
構造函數,盡管lambda函數通過引用接受其參數。 因此,在循環1中,我沒有直接訪問地圖中的對象,而只是副本。 在我的實際計划中,我需要直接訪問; 因此,我必須使用循環2指示的版本。
(事實上,環2 不調用std::pair
構造-不是一個驚喜-並沒有提供對地圖對象的直接訪問。)
我認為std::for_each
會經過精心設計,提供與for
循環相同的語義,例如Loop 2,因此不會調用std::pair
構造函數,而是允許直接訪問map中的對象。
為什么Loop 1調用std::pair
構造函數,盡管lambda函數通過引用接受它的參數?
std::map<K,V>
的value_type
是std::pair<const K, V>
。 你的lambda采用std::pair<K,V>
。 注意constness的差異。
轉換是通過以下構造函數完成的:
template< class U1, class U2 >
pair( const pair<U1, U2>& p );
(參見本參考頁面上的(4))
轉換的結果是臨時的,臨時文件可以綁定到const引用,因此您的代碼可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.