gpt4 book ai didi

c++ - 将异步与 std::accumulate 一起使用

转载 作者:太空狗 更新时间:2023-10-29 20:50:19 26 4
gpt4 key购买 nike

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

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

这有点恶心所以你可以改用 lambda:

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

关于c++ - 将异步与 std::accumulate 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com