鍍金池/ 問答/C++/ c++11 auto遍歷存儲(chǔ)線程vector

c++11 auto遍歷存儲(chǔ)線程vector

我這里已經(jīng)明白了是因?yàn)榫€程不能被復(fù)制

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

但是運(yùn)行結(jié)果得到段錯(cuò)誤,請(qǐng)問是為什么

回答
編輯回答
兮顏

最基本的問題。第一個(gè)循環(huán)里面對(duì)vector居然不用push_back

2018年7月19日 06:22
編輯回答
孤巷
#include <iostream>
#include <thread>
#include <vector>
using namespace std;

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

int main() 
{
    vector<thread> tmp(5); //未分配初始內(nèi)存,訪問tmp[i]越界
    for (int i = 0; i < 5; i++) tmp[i] = thread(Func);
    for (auto &t: tmp) t.join();
}
2017年6月5日 11:15