我正在尝试使用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;
}