Home > database >  Inserting iterable containers into map for keys and values
Inserting iterable containers into map for keys and values

Time:06-24

I have two arrays like the following. The arrays are always the same size.

std::array<int, 5> keys;
std::array<int, 5> values;

I want to load them into a map for the keys and values, respectively.

std::unordered_map<int, int> map;

for (int i = 0; i < keys.size(); i  ) {
     map.emplace(keys[i], values[i]);
}

Is there no built-in insert method or function for inserting pairs like the following?

map.insert(keys.begin(), keys.end(), values.begin(), values.end());
map.insert(keys, values);

Thanks

Note: Normally, I would be fine with iterating over the arrays to build the map but I have to do this several times.

CodePudding user response:

Yes, you can achieve the goal using STL std::transform with the help of std::inserter.

#include <iostream>
#include <unordered_map>
#include <algorithm>

using namespace std;

int main() {
    std::array<int, 5> keys{1,2,3,4,5};
    std::array<int, 5> values{10,20,30,40,50}; 
    
    std::unordered_map<int, int> map;

    transform(keys.begin(), keys.end(), values.begin(), inserter(map, map.end()), [](const int &a, const int &b) {return make_pair(a, b);}); 
    
    for (const auto &[key, val] : map) {
        cout << key << ":" << val << endl;
    } 
}

Output:

5:50
4:40
3:30
1:10
2:20
  •  Tags:  
  • c
  • Related