[英]How do I find out the type of this map in a range based for loop?
map <int, map <int, double> > adj_list_M;
我想運行一個基於范圍的 for 循環,遍歷這個地圖。 所以我想知道我可以用來獲取元素引用的類型。
另請驗證這樣做是否正確:
for( auto& ele : adj_list_M )
先感謝您!
如果要遍歷容器中的所有鍵值對,請嘗試:
for (const auto& ele : adj_list_M)
{
std::cout<<"First key in adj_list_M "<<ele.first<<std::endl;
for (const auto& sub_ele : ele.second)
{
std::cout<<"First key in sub_map : "<<sub_ele.first<<std::endl;
std::cout<<"Second value in sub_map : "<<sub_ele.second<<std::endl;
}
}
當然,因為const
關鍵字,它是只讀的。 如果要通過引用編輯鍵值對中的值,請刪除const
。
類型是pair
[key, value]
的模板是
template<typename _T1, typename _T2>
struct pair
{
typedef _T1 first_type; /// @c first_type is the first bound type
typedef _T2 second_type; /// @c second_type is the second bound type
_T1 first; /// @c first is a copy of the first object
_T2 second; /// @c second is a copy of the second object
... ...
由於 key 始終是const
,您可以使用下面的類型,
pair<const int, map<int, double>>
pair<const int, double>
map<int, map<int, double> > adj_list_M;
map<int, double> a{ { 1, 1.1 }, { 2, 2.2 } };
adj_list_M[1] = a;
for (pair<const int, map<int, double>>& ele : adj_list_M) {
cout << typeid(ele).name() << endl;
cout << ele.first << endl;
for (pair<const int, double>& subele : ele.second) {
cout << typeid(subele).name() << endl;
cout << subele.first << ":" << subele.second << endl;
}
}
輸出:
St4pairIKiSt3mapIidSt4lessIiESaIS_IS0_dEEEE
1
St4pairIKidE
1:1.1
St4pairIKidE
2:2.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.