gpt4 book ai didi

c++ - 试图将 vector 的内容传递给线程

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:59 25 4
gpt4 key购买 nike

我有一个接受字符串 vector 的函数,我在一个 vector 中有一系列这些字符串 vector 。

我想遍历 vector ,将每个字符串 vector 传递给新线程。

for (vector<vector<string> >::iterator it = vecstringvec.begin() ; 
it != vecstringvec.end(); ++it){
threadvector.push_back(thread(func, *it));
}

基本上是上面的,除了上面的不起作用(编译错误)。我相信我需要一个 std::ref 的 vector 来传递,但我不确定,或者如何使用迭代器来做到这一点。

完整错误:

/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::vector<std::basic_string<char> >, std::reference_wrapper<std::vector<std::basic_string<char> > >))(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >&)>’:
/usr/include/c++/4.8/thread:137:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >&); _Args = {std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&, std::reference_wrapper<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >}]’
prog.cpp:199:55: required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<std::basic_string<char> >, std::reference_wrapper<std::vector<std::basic_string<char> > >))(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >&)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<std::basic_string<char> >, std::reference_wrapper<std::vector<std::basic_string<char> > >))(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >&)>’
_M_invoke(_Index_tuple<_Indices...>)
^
make: *** [prog.o] Error 1

最佳答案

查看错误消息,func() vector 参数是按引用传递而不是按值传递。尝试使用 std::ref(*it)

引用 cppreference :

The arguments to the thread function are copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g. with std::ref or std::cref).

例子:

#include <vector>
#include <thread>
#include <iostream>

void func(const std::vector<int>& value)
{
std::cout << "Value: " << value.size() << std::endl;
}

int main(int argc, char const *argv[])
{
std::vector<std::vector<int>> values =
{ { 1, 2 } , { 1, 2, 3 }, { 1, 2, 3, 4 } };

std::vector<std::thread> threads;
for (auto& vect: values)
{
threads.emplace_back(func, std::cref(vect));
}

for (auto& thread: threads)
{
thread.join();
}

return 0;
}

(顺便说一句,如果有一个完整的独立示例,诊断会容易得多)。

关于c++ - 试图将 vector 的内容传递给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24971831/

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