从 2D 矢量获取输入时出现分段错误
Segmentation Fault while getting input from 2D vector
当我 运行 下面的代码时出现分段错误。
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
的值是什么,我都会得到同样的错误。
你从来没有告诉过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
}
}
}
当我 运行 下面的代码时出现分段错误。
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
的值是什么,我都会得到同样的错误。
你从来没有告诉过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
}
}
}