c++11 auto遍历存储线程vector

我这里已经明白了是因为线程不能被复制

#include <iostream>
#include <thread>
#include <vector>
using namespace std;

void Func() 
{
    cout << "hello world" << endl;
}

int main() 
{
    vector<thread> tmp;
    for (int i = 0; i < 5; i++) 
    {
        tmp[i] = thread(Func);
    }

    for (auto it : tmp) 
    {
        //
    }
}

于是我尝试使用迭代器
像这样

#include <iostream>
#include <thread>
#include <vector>
using namespace std;

void Func() 
{
    cout << "hello world" << endl;
}

int main() 
{
    vector<thread> tmp;
    for (int i = 0; i < 5; i++) 
    {
        tmp[i] = thread(Func);
    }

    for (auto it = tmp.begin(); it != tmp.end(); it++) 
    {
        it->join();
    }
}

但是运行结果得到段错误,请问是为什么

阅读 4.7k
2 个回答

最基本的问题。第一个循环里面对vector居然不用push_back

#include <iostream>
#include <thread>
#include <vector>
using namespace std;

void Func() 
{
    cout << "hello world" << endl;
}

int main() 
{
    vector<thread> tmp(5); //未分配初始内存,访问tmp[i]越界
    for (int i = 0; i < 5; i++) tmp[i] = thread(Func);
    for (auto &t: tmp) t.join();
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题