Reputation: 47
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. 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. I tried using iterator->second.first
and 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.
Upvotes: 1
Views: 9689
Reputation: 3850
Yes, this is correct, but don't use tr1
, write std
, since unordered_map
is already part of 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
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
for(auto it = sWeight.begin(); it != sWeight.end(); ++it) {
auto& p = it->second;
std::cout << it->first << ": "
<< p.first << ", "
<< p.second << std::endl;
}
Upvotes: 2