I am trying to go from a std::unordered_multimap<uint, T> lookup
to a std::vector<T> v
So far I tried
std::vector<T> v(lookup.begin(), lookup.end());
but it obviously doesn't work since the resulting iterators of begin()
and end()
are of type pair<uint, T>
, so what would be the fastest correct way to do this?
Thank you for your help!
Extract the value part of the std::pair
in the hash map and put it into the vector:
#include <iostream>
#include <unordered_map>
#include <vector>
int main() {
using Map = std::unordered_multimap<int, int>;
auto m = Map { {1, 1}, {1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6} };
std::vector<int> v;
v.reserve(m.size());
for (auto const& elem : m)
v.push_back(elem.second);
for (auto const& elem : v)
std::cout << elem << "\n";
}
Note that with C++11, you can use a ranged for-loop + auto
to avoid having to explicitly express the type of the map elements. Furthermore, you can use the initializer-list syntax to quickly init the map as well.
NOTE: in practical examples, please do use the reserve()
on the vector so as to avoid excessive memory allocations.
Live Example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With