c++ - 我怎样才能从这个“调试断言失败!”中找到我的编码错误在哪里?错误?
问题描述
我只是通过终端运行我的代码,然后“调试断言失败!” 弹出错误提示“向量下标超出范围”。这是我第一次遇到这种错误,所以我不确定如何在我的代码中找到错误所在。也许这很明显,因为我对 C++ 还很陌生,而且我不太擅长找出错误所在。以下是我的代码,所以如果您发现需要更正的内容,请告诉我。谢谢!
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Node {
int data;
Node* right, * down;
};
Node* construct(vector<vector<int>> arr, size_t i, size_t j, size_t m, size_t n)
{
if (i > n - 1 || j > m - 1)
return NULL;
Node * temp = new Node();
temp->data = arr[i][j];
temp->right = construct(arr, i, j + 1, m, n);
temp->down = construct(arr, i + 1, j, m, n);
return temp;
}
void display(Node * head)
{
Node* Rp;
Node* Dp = head;
// loop till node->down is not NULL
while (Dp) {
Rp = Dp;
// loop till node->right is not NULL
while (Rp) {
cout << Rp->data << " ";
Rp = Rp->right;
}
cout << "\n";
Dp = Dp->down;
}
}
int main(int argc, char* argv[])
{
if ((argc == 2) && (string(argv[1]) == "-Stack"))
{
int K;
cin >> K; //getting the number of rooms from the text file
for (int i = 0; i < K; ++i) //a loop for each room
{
int M = 0; // initializing rows variable
int N = 0; // initializing columns variable
cin >> M >> N;
vector<vector<int> > matrix(M); //give a matrix with a dimension M*N with all elements set to 0
for (int i = 0; i < M; i++)
matrix[i].resize(N);
for (int i = 0; i < M; i++) //adding each row to the matrix
{
for (int j = 0; j < N; j++) //adding each column to the matrix
{
cin >> matrix[i][j]; //putting all the elements in the matrix
}
}
size_t m = M, n = N;
Node* head = construct(matrix, 0, 0, m, n);
display(head);
return 0;
}
}
else if ((argc == 2) && (string(argv[1]) == "-Queue"))
{
int K;
cin >> K; //this grabs the number of rooms in the dungeon
cout << K;
}
}
解决方案
许多运行时错误并非发生在错误的确切位置,而是在您使用的调试工具的帮助下发生在某处。
例如,如果您尝试写入std::vector
过去的大小,那么它的调试版本可能会进行边界检查并在其上抛出异常(调试器还插入堆栈帧陷阱以检查缓冲区溢出等)。
此异常不会出现在错误的确切行,而是出现在后面的代码中。
您可以使用调试器的调用堆栈功能来准确查找错误所在的位置。
例子:
vector<int> x(10);
x[10] = 1; // Calls vector::operator[]
// in vector::operator[]
if(i >= size())
throw; // This is where the exception is thrown
调用堆栈将帮助您从throw
行转到x[10] = 1
错误所在的行。
推荐阅读
- json - NodeJS - 无法确定/验证传入的表单数据,因为所有这些数据都被视为字符串
- python-3.x - 为什么只创建一个周期性任务?
- javascript - 为什么我不能推送到 Vue 数组并让它工作?
- rdma - 动词 API 中的 RDMA 分散/聚集
- r - 如何返回来自不同组的最后 n 行的平均值(由变量表示)
- html - 如何:如何创建空间/移动从最后一个 div 移动一个 div,而不是完全移动到页面
- tensorflow - a3c连续动作问题
- php - PHP - SQL:将两行组合成具有多列的单行
- perl - Perl - 从引用的@array 中删除重复项
- xamarin - 如何为 Xamarin 表单中的条目提供动态填充?