Quickly set values in map over range C++

Viewed 102

I need to set all the values in a map within a range of (0,N) to false. When I simply iterate over the range and set the value, it is rather slow, with the below example taking about 300 microseconds.

#include <map>

std::map<int, bool> mp;
int N = 600;

for (int i = 0; i < N; i++) {
    mp[i] = false;
}

Is there a faster way to do this?

1 Answers

The version below takes advantage of the fact that you can to this in parallel. async executes the tasks in a separate thread (also see launch-policy).

The sequential approach takes 0.016s and the parallel approach takes 0.006s.

#include <vector>
#include <map>
#include <memory>
#include <future>

// end exclusive
void set_m(int begin, int end, std::shared_ptr<std::map<int, bool>> mp)
{
    for (int i = begin; i < end; i++)
    {
        mp->insert({i, false});
    }
}

int main()
{
    auto mp = std::make_shared<std::map<int, bool>>();
    // takes 0m0.016s
    set_m(0, 6000 + 1, mp);

    // takes 0m0.006s
    std::vector<std::future<void>> v;
    for (int i = 0; i < 6000; i += 1000)
    {
        v.push_back(std::async(set_m, i, i + 1001, mp));
    }
    for (std::future<void> &a : v)
    {
        a.wait();
    }
    return 0;
}
Related