将异步与std ::累积

Using async with std::accumulate

本文关键字:累积 std 异步      更新时间:2023-10-16

我认为这会更简单,但是尝试了以下许多变体,我无法将此代码编译

#include <thread>
#include <algorithm>
#include <future>
int main()
{
    std::vector<int> vec(1000000, 0);
    std::future<int> x = std::async(std::launch::async, std::accumulate, vec.begin(), vec.end(), 0);
}

error: no matching function for call to 'async(std::launch, <unresolved overloaded function type>, std::vector<int>::iterator, std::vector<int>::iterator, int)'

我缺少什么?

,因为std::accumulate是一个模板,您必须在获取地址之前提供模板参数(将其解析为特定函数)。

#include <thread>
#include <algorithm>
#include <future>
#include <vector>
#include <numeric>
int main()
{
    std::vector<int> vec(1000000, 0);
    std::future<int> x = std::async(std::launch::async,
        &std::accumulate<std::vector<int>::const_iterator, int>,
            vec.begin(), vec.end(), 0);
}

那是一种uck,所以您可以使用lambda:

std::future<int> x = std::async(std::launch::async,
    [&]{ return std::accumulate(vec.begin(), vec.end(), 0); });