为什么我的 c++ 程序崩溃了
Why is my c++ program crashing?
#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];
}
}
每次我给输入m
和n
,它都会崩溃!我正在尝试做的是将输入提供给m
行和n
列的二维数组。
您需要在
读取 m
和 n
的值后初始化向量(或调整其大小)。 正如您所看到的,当向量初始化时,m
和n
为 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();
}
相关文章:
- 提升 ASIO Async_receive崩溃程序
- 类指针方法崩溃程序
- get_body来自 IHTMLDocument2 崩溃程序
- 是否有可能存在不会崩溃程序的内存问题
- 调试运行时出现奇怪的崩溃程序(Eclipse C++)
- 儿童对话框 - setWindowTexta或sendmessagea崩溃程序-MFC
- 顶点阵列GLFW崩溃C 程序
- 将值分配给Float数据类型崩溃程序
- OpenCV-将变量添加到类成员崩溃程序
- boost::interprocess::managed_shared_memory 崩溃程序
- 将枚举值分配给整数崩溃程序
- SDL 1.2 -> SDL 2.0(崩溃程序)
- 空析构函数崩溃程序:C++
- 冒泡排序崩溃程序c++
- Ofstream关闭崩溃程序
- 删除字符* 崩溃程序
- c++矢量擦除崩溃程序
- Lua_getglobal崩溃程序
- 通过Copy Constructor创建的e2打印崩溃程序
- RNG崩溃c++程序