How to convert a array enumeration to map efficiently

Viewed 88


I am looking for an efficient way of converting a C++ array to a map according to the array index enumeration.

For example, if I have an array with

arr=[2,4,5,3,6]

I want to get a map like

[<0,2>, <1,4>, <2,5>, <3,3>, <4,6>]

My current implementation is like this:

std::map<int, int> mapping; 
for (int i = 0; i < len; i++)
    mapping.insert(pair<int, int>(i, arr[i]));
2 Answers

With the range-v3 library, you could write this conveniently, and quite readably, and it's efficient as well:

namespace rs = ranges;
namespace rv = ranges::views;

auto result = input 
            | rv::enumerate 
            | rs::to<std::map<int, int>>;

Here's a demo.

You could speed it up a bit by giving a hint on the insertion.

std::map<int, int> mapping; 
for (int i = 0; i < len; i++)
    mapping.emplace_hint(mapping.end(), i, arr[i]);
Related