![](/img/trans.png)
[英]Unordered_map of unordered_map vs custom hash function for pair key C++?
[英]unordered_map pair of values c++
我試圖在C ++中使用unordered_map
,這樣,對於鍵,我有一個int
,而對於值,則有一對浮點數。 但是,我不確定如何訪問這對值。 我只是想弄清楚這個數據結構。 我知道要訪問這些元素,我們需要與該無序映射聲明具有相同類型的iterator
。 我嘗試使用iterator->second.first
和iterator->second.second
。 這是訪問元素的正確方法嗎?
typedef std::pair<float, float> Wkij;
tr1::unordered_map<int, Wkij> sWeight;
tr1::unordered_map<int, Wkij>:: iterator it;
it->second.first // access the first element of the pair
it->second.second // access the second element of the pair
感謝您的幫助和時間。
是的,這是正確的,但是不要使用tr1
,而是寫std
,因為unordered_map
已經是STL的一部分。
像你說的那樣使用迭代器
for(auto it = sWeight.begin(); it != sWeight.end(); ++it) {
std::cout << it->first << ": "
<< it->second.first << ", "
<< it->second.second << std::endl;
}
同樣在C ++ 11中,您可以使用基於范圍的for循環
for(auto& e : sWeight) {
std::cout << e.first << ": "
<< e.second.first << ", "
<< e.second.second << std::endl;
}
而且,如果您需要它,您可以像這樣使用std::pair
for(auto it = sWeight.begin(); it != sWeight.end(); ++it) {
auto& p = it->second;
std::cout << it->first << ": "
<< p.first << ", "
<< p.second << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.