在C++中遍历映射的一部分
Iterate through part of a map in C++
如何在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() );
}
假设所有字符串都是小写的。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 在未初始化映射的情况下,将值插入到映射的映射中
- QT通过C++添加映射QML项目
- 在c++中访问int到类对象的映射时出错
- 在C++中搜索嵌套多映射值
- 从另一个常量标准::映射初始化一个常量标准::映射的一部分
- 如何制作一个C++映射容器,其中键是值的一部分
- 复制存储在内存映射文件中的数组的一部分
- 检查字符串是否是映射的一部分
- 在C++中遍历映射的一部分