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

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


GCT1015
浏览 1838回答 2
2回答

AAnonymous

错误贴出来另外,你觉得 for (auto it : tmp) 有值拷贝的话,换成引用就没有拷贝了 for (auto &it : tmp)

呼唤远方

最基本的问题。第一个循环里面对vector居然不用push_back
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript