1

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.

2
  • 1
    unordered_map is part of the C++11 standard , you can use std:: instead of tr1:: Commented Apr 23, 2015 at 11:14
  • 1
    you could also use std::get<0>(it->second), or std::get<0>(std::get<1>(*it)) (both gives it->second.first, which is perfectly valid) Commented Apr 23, 2015 at 11:31

1 Answer 1

2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.