首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在C++中迭代地图的一部分

在C++中迭代地图的一部分
EN

Stack Overflow用户
提问于 2013-02-27 08:08:27
回答 2查看 422关注 0票数 1

如何在C++中只迭代映射的一部分?我的最终目标是让多个线程迭代其映射的一部分,并计算一些值。地图类型为std::map<std::string, std::vector<double> >

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-27 08:26:45

以下是在C++11中完成此操作的简单方法:

代码语言:javascript
运行
复制
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <future>
#include <iostream>

typedef std::map<std::string, std::vector<double>> map_type;

void do_work(map_type::iterator b, map_type::iterator e)
{
    std::for_each(b, e, [] (map_type::value_type const& p) 
    {
        std::for_each(p.second.begin(), p.second.end(), [] (double d) 
        {
            /* Process an element of the vector... */
        });
    });
}

int main()
{
    map_type m;

    size_t s = m.size();
    int quarter = s / 4;
    auto i1 = m.begin();
    auto i2 = std::next(i1, quarter);
    auto i3 = std::next(i2, quarter);
    auto i4 = std::next(i3, quarter);
    auto i5 = m.end();

    std::vector<std::future<void>> futures;
    futures.push_back(std::async(do_work, i1, i2));
    futures.push_back(std::async(do_work, i2, i3));
    futures.push_back(std::async(do_work, i3, i4));
    futures.push_back(std::async(do_work, i4, i5));

    for (auto& f : futures) { f.wait(); }
}
票数 2
EN

Stack Overflow用户

发布于 2013-02-27 08:22:44

如果您想按数字平均划分工作,那么map可能不是最好的数据结构。您需要遍历map并查找特定位置的迭代器。如果你使用提供随机访问迭代器的容器,比如std::vector,那么你可以算术地计算迭代器。如果你想按字母顺序排列,你可以这样做:

代码语言:javascript
运行
复制
typedef std::map<std::string,std::vector<double>> data;

void process( data::iterator beg, data::iterator end );
data dt;
{
   auto task1 = std::async( process, dt.begin(), dt.lower_bound( "n" ) );
   auto task2 = std::async( process, dt.lower_bound( "n" ), dt.end() );
}

假设所有字符串都是小写的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15101888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档