2015-04-23 67 views
1

我想在C++中使用unordered_map,因此,对于密钥我有一个int,而对于该值则有一对浮点数。但是,我不确定如何访问这对值。我只是想弄明白这个数据结构。我知道要访问我们需要的iterator这个无序的映射声明的相同类型的元素。我尝试使用iterator->second.firstiterator->second.second。这是做访问元素的正确方法吗?unordered_map对值C++

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 

感谢您的帮助和时间。

+3

它编译? –

+1

'unordered_map'是C++ 11标准的一部分,你可以使用'std ::'而不是'tr1 ::' – Alejandro

+1

你也可以使用'std :: get <0>(it-> second)'或' std :: get <0>(std :: get <1>(* it))'(都给出了它 - > second.first,这是完全有效的) –

回答

2

是的,这是正确的,但不要使用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(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; 
} 
+0

谢谢@NikolayKondratyev。这非常有帮助! – TMath