當我在向量中保留空間時,我不明白為什么它說下標超出范圍。我創建了我的代碼的簡短形式來解釋問題更好:
#include <vector>
#include <string>
#include <thread>
#include <iostream>
using namespace std;
class A {
public:
vector<vector<string>> foo;
thread* aThread;
A() {
foo.reserve(10); //makes sure we have space...
aThread = new thread([this]() {
for (int i = 0; i < 10; i ) {
foo[i].push_back("Hello"); // Debug assertion failed. :(
}
});
}
};
int main()
{
A a;
a.aThread->join();
for (int i = 0; i < 10; i ) {
for (int j = 0; j < a.foo.size(); j ) {
cout << a.foo[i][j] << " ";
}
cout << endl;
}
return 0;
}
只要我嘗試將元素添加到執行緒內的 foo 向量中,它就會在此處給出錯誤。我無法弄清楚出了什么問題。請幫忙。
uj5u.com熱心網友回復:
foo.reserve(10)
為 foo 中的元素保留空間,但它不會使用空的 std::vector 填充任何元素。
您可以將其更改為:
foo.resize(10);
這將保留空間并創建空 vector< string > 元素,以便您可以訪問它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475621.html
