Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dump an std::unordered_multimap<uint, T> to a std::vector<T>?

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!

like image 710
Luis Yanes Avatar asked Dec 15 '22 20:12

Luis Yanes


1 Answers

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.

like image 61
TemplateRex Avatar answered Feb 06 '23 14:02

TemplateRex