可以使用与您链接的答案中采用的方法类似的方法来完成。我们面临的一个问题是std::transform 在地图方面使用了一条不幸的线。
//GCC version, but the documentation suggests the same thing.
*__result = __binary_op(*__first1, *__first2);
由于地图存储类型std::pair<const T1, T2>(即第一个必须始终为const,您不能修改键),这会导致错误,因为operator=在这种情况下被删除。
出于这个原因,我们最终不得不自己编写整个事情(下面的答案可能会更简洁,我只是硬编码了你的类型......)。
我们可以从std::transform (look at example implementation 2) 的示例开始并修改有问题的部分,但是@Zulan 在 cmets 中提出了一个很好的观点,即同时遍历无序映射可能不是一个好主意(因为它们是,根据定义,未排序)。虽然复制构造函数保留顺序可能有一定意义,但标准似乎无法保证这一点(至少我在任何地方都找不到),因此std::transform 采用的方法变得非常无用。
我们可以通过稍微不同的缩减来解决这个问题。
#include <unordered_map>
#include <string>
#include <iostream>
#include <utility>
void reduce_umaps(\
std::unordered_map<std::string, double>& output, \
std::unordered_map<std::string, double>& input)
{
for (auto& X : input) {
output.at(X.first) += X.second; //Will throw if X.first doesn't exist in output.
}
}
#pragma omp declare reduction(umap_reduction : \
std::unordered_map<std::string, double> : \
reduce_umaps(omp_out, omp_in)) \
initializer(omp_priv(omp_orig))
using namespace std;
unordered_map<string, double> umap {{"foo", 0}, {"bar", 0}};
string some_string(int in) {
if (in % 2 == 0) return "foo";
else return "bar";
}
inline double some_double(int in) {
return static_cast<double>(in);
}
int main(void) {
#pragma omp parallel for reduction(umap_reduction:umap)
for (int i = 0; i < 100; ++i) {
umap.at(some_string(i)) += some_double(i);
}
std::cerr << umap["foo"] << " " << umap["bar"] << "\n";
return 0;
}
您也可以将其概括为允许在并行循环中添加键,但这不会很好地并行化,除非添加的键的数量仍然远小于您增加值的次数。
作为最后的附注,我用umap.at(some_string(i)) 替换了umap[some_string(i)],以避免意外添加元素,就像在 cmets 中建议的那样,但find 并不是最实用的功能。