c++ - 在 C++ 范围内快速设置 map 中的值

标签 c++ stl assign stdmap

我需要将 map 中的所有值设置在 (0,N)false 范围内。当我简单地遍历范围并设置值时,速度相当慢,下面的示例大约需要 300 微秒。

#include <map>

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

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

有没有更快的方法来做到这一点?

最佳答案

下面的版本利用了您可以并行执行此操作的事实。 async在单独的线程中执行任务(另见 launch-policy )。

顺序方法需要 0.016 秒,并行方法需要 0.006 秒。

#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;
}

关于c++ - 在 C++ 范围内快速设置 map 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61991220/

相关文章:

c++ - 警告 : specialization of template in different namespace

javascript - 将纹理叠加到 STL 加载的网格上

c++ - 结构指针的优先级队列

ostringstream 的 C++ 奇怪行为

javascript - 如何用变量替换 javascript yahoo 天气 api 调用属性

c++ - 标准库函数 abs() 在不同 C++ 编译器上的异常行为

c++ - 消息映射如何与 SendMessage() 方法交互?

c++ - auto 作为常规函数中的参数是 GCC 4.9 扩展吗?

match - perl6 语法 Action : unable to make anything if not using $/

c++ - 分析变量赋值的 bool 结果有意义吗?