在C++中遍历映射的一部分

Iterate through part of a map in C++

本文关键字:一部分 映射 遍历 C++      更新时间:2023-10-16

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

这里有一个在C++11中实现它的简单方法:

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

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

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() );
}

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