運行以下代碼時出現分段錯誤。
int main()
{
int R, C, val;
cin>>R>>C;
vector<vector<int>> a;
for(int i = 0; i < R; i )
{
for(int j = 0; j < C; j )
{
cin>>val;
a[i].push_back(val);
}
}
但是當我把它改成這個時,它似乎起作用了。是什么原因?
int main()
{
int R, C, val;
cin>>R>>C;
vector<vector<int>> a;
for(int i = 0; i < R; i )
{
vector<int>temp;
for(int j = 0; j < C; j )
{
cin>>val;
temp.push_back(val);
}
a.push_back(temp);
}
無論R和的值C是多少,我都會遇到同樣的錯誤。
uj5u.com熱心網友回復:
你從來沒有告訴過它的大小vector<vector<int>>,你嘗試訪問a[i]。
您必須調整向量的大小。
int main()
{
int R, C;
std::cin >> R >> C;
std::vector<std::vector<int>> a(R, std::vector<int>(C));
for(int i = 0; i < R; i )
{
for(int j = 0; j < C; j )
{
std::cin >> a[i][j]; //because we resize the vector, we can do this
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371699.html
