C++ 在std::vector中并行调用函数

C++ 在std::vector中并行调用函数,c++,c++14,C++,C++14,我有一个std::vector的std::function如下: std::map<Event, std::vector<std::function<void()>>> observers_; for (const auto& obs : observers_.at(event)) obs(); 我想把它变成一个并行for循环。由于我使用的是C++14,并且无法访问C++17的std::execution::parallel,因此我找到了一个可以创

我有一个
std::vector
std::function
如下:

std::map<Event, std::vector<std::function<void()>>> observers_;
for (const auto& obs : observers_.at(event)) obs();
我想把它变成一个并行for循环。由于我使用的是
C++14
,并且无法访问
C++17
std::execution::parallel
,因此我找到了一个可以创建线程池的小库

如何为(const auto&obs:observators_.at(event))obs()打开
转换为并行调用
observators\中的每个函数的版本?我似乎不能理解正确的语法。我试过了,但没用

std::vector<std::function<void()>> vec = observers_.at(event);
ThreadPool::ParallelFor(0, vec.size(), [&](int i)
{
    vec.at(i);
});
std::vector vec=观察者(事件);
ThreadPool::ParallelFor(0,vec.size(),[&](int i)
{
向量at(i);
});
使用以下库的示例程序:

#include <iostream>
#include <mutex>

#include "ThreadPool.hpp"
////////////////////////////////////////////////////////////////////////////////

int main()
{
    std::mutex critical;
    ThreadPool::ParallelFor(0, 16, [&] (int i)
    {
        std::lock_guard<std::mutex> lock(critical);
        std::cout << i << std::endl;
    });
    return 0;
}
#包括
#包括
#包括“ThreadPool.hpp”
////////////////////////////////////////////////////////////////////////////////
int main()
{
互斥临界;
ThreadPool::ParallelFor(0,16,[&](inti)
{
标准:锁紧/防护锁(关键);

提示:这是做什么用的

vec.at(i);
你想让它做什么



最近,您使用的是
at()
,意思是
[]

似乎您只需更改:

vec.at(i); // Only returns a reference to the element at index i
进入:

这项工作:

ThreadPool::ParallelFor(0, (int)vec.size(), [&] (int i)
{
    vec[i]();
});

说得好。我需要休息一下。不过,如果我说ThreadPool::ParallelFor(0,vec.size(),[&]vec[I]),我没有被宣布?我怎么才能证明我的索引是什么?是的,在Barry指出之后,剩下的很简单。累了。谢谢。我被否决票弄糊涂了。这是一个错误的解决方案吗?
vec.at(i)(); // The second () calls the function
--- OR ---
vec[i](); // Same
ThreadPool::ParallelFor(0, (int)vec.size(), [&] (int i)
{
    vec[i]();
});