如果這個問題看起來很簡單,我很抱歉。我仍然在學習線程。我已經嘗試過在這裏尋找解決方案,但沒有找到任何解決方案。我試圖讓我的程序根據用戶輸入創建一些線程(例如:「cin >> 5」將創建5個線程),但它說「我在」線程myThreads [我] 「需要是一個不變的價值。代碼如下:程序根據用戶輸入不工作(cin)創建一些線程?
void exec(int n)
{
cout << "Thread " << n << endl;
}
int main()
{
int numThreads = 0;
// create threads
cin >> numThreads;
thread myThreads[numThreads]; // this part says myThreads "must be a constant value"
for (int i = 0; i < numThreads; i++)
{
myThreads[i] = thread(exec, i);
}
for (int i = 0; i < numThreads; i++)
{
myThreads[i].join();
}
cout << "Done!" << endl;
}
有關如何修復該部分的任何想法?我嘗試了幾種不同的方法,但迄今爲止還沒有奏效。非常感謝你。
你試過使用'std :: vector'嗎? (例如'std :: vector myThreads(numThreads);') –