我正在尝试unordered_map
在C ++中使用,因此,对于键,我有一个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
,write 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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句