我有一个unordered_map
的vectors
,我正在尝试使用std::reduce
来获取地图中所有向量中所有值的总和。我当前的功能代码(我想要替换)看起来像这样:
// input is std::unordered_map<std::vector<uint64_t>>
template<typename T>
uint64_t get_map_sum(T& my_map)
{
uint64_t totalcount = 0;
for (auto& p : my_map)
{
for (const auto& q : p.second)
totalcount += q;
}
return total_count;
}
我想用std::reduce
替换它来利用并行执行;我认为这将是直截了当的,因为我只需要通过调用std::reduce
来替换每个循环,但这似乎不起作用。我的尝试是这样的:
#include <numeric>
#include <execution>
#include <vector>
#include <unordered_map>
#include <cstdint>
// reduces the vectors
template <typename Iter, typename T>
T get_vector_sum(Iter begin, Iter end, T initial = 0)
{
return std::reduce(std::execution::par_unseq, begin, end, initial,
[&](auto cur, auto prev) { return cur + prev; });
}
// calls get_vector_sum for all vectors and then reduces vector sums
template<typename Iter>
uint64_t get_map_sum(Iter begin, Iter end)
{
return std::reduce(std::execution::par_unseq, begin, end, 0ULL,
[&](auto prev, auto cur)
{
return get_vector_sum<std::vector<uint64_t>::iterator,
uint64_t>(cur.begin(), cur.end(), prev);
//return get_vector_sum<std::vector<uint64_t>::iterator,
// uint64_t>(cur.second.begin(), cur.second.end(), prev);
});
}
使用上面的代码,我得到一条错误消息,说error C2039: 'begin': is not a member of 'std::pair'
指的是auto cur
里面的lambda中的get_map_sum
。我最初使用cur
作为std::pair
,但是当我这样做时,我得到了一个不同的错误,说error C2228: left of '.second' must have class/struct/union
。
int main()
{
std::unordered_map<uint64_t, std::vector<uint64_t>> in({
{1, std::vector<uint64_t>{1,2,3,4,5} },
{2, std::vector<uint64_t>{1,2,3,4,5}},
{3, std::vector<uint64_t>{1,2,3,4,5}}});
auto x = get_map_sum(in); // output 45
auto y = get_map_sum(in.begin(), in.end()); // error
return 0;
}
是否可以将std::reduce
与这样的地图一起使用,如果是这样,我需要做些什么改变才能使其正常工作?
请注意std::reduce
的binary_op的这个要求:
二进制FunctionObject,将以未指定的顺序应用于取消引用输入迭代器的结果,其他binary_op和init的结果。
这意味着lambda结果和init的结果需要与map的值类型相同,即std::pair<const uint64_t, std::vector<uint64_t>>
。
因此,您需要对此类型的值执行外部缩减,这将涉及构造新向量。
我还试图创建一个示例代码如下:
using M = std::unordered_map<uint64_t, std::vector<uint64_t>>;
using V = M::value_type;
M in({ {1, std::vector<uint64_t>{1,2,3,4,5}},
{2, std::vector<uint64_t>{1,2,3,4,5}},
{3, std::vector<uint64_t>{1,2,3,4,5}} });
auto p = std::reduce(in.begin(), in.end(), V{},
[](const V& a, const V& b) {
auto ra = std::reduce(a.second.begin(), a.second.end(), 0UL,
[](uint64_t i1, uint64_t i2){ return i1 + i2; });
auto rb = std::reduce(b.second.begin(), b.second.end(), 0UL,
[](uint64_t i1, uint64_t i2){ return i1 + i2; });
return V{0, { ra + rb }};
});
但由于看似缺少std::reduce
实现,它不会与GCC一起编译,而且Clang抱怨缺少值类型的复制赋值运算符,由于const键:https://wandbox.org/permlink/FBYAhCArtOHvwu8C而不能复制赋值。
但是,在cppreference中,值类型的要求只是MoveConstructible,而不是Copy / MoveAssignable。所以,libc ++中的实现似乎不正确。
在这个示例代码中,我能够通过定义没有const的qazxsw poi来使其工作,如下所示:
V
见using V = std::pair<uint64_t, std::vector<uint64_t>>;
。
我们只需要提供一个可以从https://wandbox.org/permlink/lF9VuJwISYXhpBJL隐式转换的类型,而不是将向量构造为中间结果。
M::value_type