为什么我的 c++ 程序崩溃了

Why is my c++ program crashing?

本文关键字:崩溃 程序 c++ 我的 为什么      更新时间:2023-10-16
#include <iostream>
#include <vector>
using namespace std;
int m,n;
vector<vector<int> > name(m,vector<int>(n));
int main()
{
    cin>>m>>n;
    for ( int i=0;i<m;i++)
    {
        for( int j=0;j<n;j++)
            cin>>name[i][j];
    }
}

每次我给输入mn,它都会崩溃!我正在尝试做的是将输入提供给m行和n列的二维数组。

您需要在

读取 mn 的值初始化向量(或调整其大小)。 正如您所看到的,当向量初始化时,mn为 0*,因此向量的大小为 0。

*这只是因为您将它们放置在全局范围内。 如果将它们放置在函数中,它们将未初始化,并且使用它们的值将是未定义的行为

因为你已经超出了界限。

name向量是全局变量,因此它在程序启动时初始化,甚至在函数main之前。此外,整数全局变量在 C++ 中使用 0 初始化。因此,name向量的大小为零。

读取n值并m值后,您需要调整矢量的大小。

Error is you are trying to access the index out of bound

因为您的名字不是 2D 矢量。

请改用此代码将name设为 2D 矢量。

vector < vector <int> > name;
vector<int > col;
int r, c;
void main()
{
    cin >> r;
    cin >> c;
    for (int i = 0; i < c; i++)
    {
        col.push_back(i);//push i to col just to make it size of columns needed
    }
    for (int i = 0; i < r; i++)
    {
        name.push_back(col);//pushing vector col of size c into name to 
        //make it a 2D vecotr
    }
    //now name is a 2D vector with r rows of each c column
    cout << "nNow Enter values";
    for (int i = 0; i < r; i++)
    {
        for (int j = 0; j < c; j++)
        {
            cin >> name[i][j];//input values
        }
    }
    getch();

}