[英]unordered_map pair of values c++
I am trying to use the unordered_map
in C++, such that, for the key I have an int
, while for the value there is a pair of floats. 我试图在C ++中使用unordered_map
,这样,对于键,我有一个int
,而对于值,则有一对浮点数。 But, I am not sure how to access the pair of values. 但是,我不确定如何访问这对值。 I am just trying to make sense of this data structure. 我只是想弄清楚这个数据结构。 I know to access the elements we need an iterator
of the same type as this unordered map declaration. 我知道要访问这些元素,我们需要与该无序映射声明具有相同类型的iterator
。 I tried using iterator->second.first
and iterator->second.second
. 我尝试使用iterator->second.first
和iterator->second.second
。 Is this the correct way to do access elements? 这是访问元素的正确方法吗?
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
Thanks for your help and time. 感谢您的帮助和时间。
Yes, this is correct, but don't use tr1
, write std
, since unordered_map
is already part of STL. 是的,这是正确的,但是不要使用tr1
,而是写std
,因为unordered_map
已经是STL的一部分。
Use iterators like you said 像你说的那样使用迭代器
for(auto it = sWeight.begin(); it != sWeight.end(); ++it) {
std::cout << it->first << ": "
<< it->second.first << ", "
<< it->second.second << std::endl;
}
Also in C++11 you can use range-based for loop 同样在C ++ 11中,您可以使用基于范围的for循环
for(auto& e : sWeight) {
std::cout << e.first << ": "
<< e.second.first << ", "
<< e.second.second << std::endl;
}
And if you need it you can work with std::pair
like this 而且,如果您需要它,您可以像这样使用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.