c++程序停止工作
C++ - program has stopped working
我下面发布的代码应该在递归(Sort()函数)中工作,甚至高达1kk次。问题是:当Sort()函数进入循环编号43385时,控制台停止工作并发出警报:"程序已停止工作"。是记忆力的问题吗?如果是,代码中不好的部分在哪里?问候。
#include <iostream>
#include <string>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
if(i==n-1)
return counter;
else
Sort(i+1);
}
int main()
{
cin >> n >> a >> b;
Sort(0);
return 0;
}
可能是调用堆栈溢出,因为太深的递归?
要添加到iltal的注释中,您可能希望打印出字符串a, b的信息:a.size(), a.length(), a.capacity(), a.max_size()
我不确定这段代码要做什么。下面是一个修改版,添加了一些打印语句,以及一个随机字符串生成器。
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
cout << "x = " << x << " set tmp0 to " << tmp0 << " and tmp1 to " << tmp1 << endl;
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
cout << " endof sort: a is " << a << endl;
cout << " b is " << b << endl;
if(i==n-1) {
cout << "Returning counter " << counter << endl;
return counter;
} else {
cout << "Running sort(" << i << " + 1)" << endl;
Sort(i+1);
}
}
string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
int main()
{
n = 50;
srand(time(NULL));
string a0, b0;
a0 = randomStrGen(n);
a = a0;
b0 = randomStrGen(n);
b = b0;
// cin >> n >> a >> b;
cout << "Max string size is " << a.max_size() << endl;
cout << "Calling sort" << endl
<< " n is " << n << endl
<< " a is " << a << endl
<< " b is " << b << endl;
Sort(0);
cout << " endof program: a inital: " << a0 << endl;
cout << " a final: " << a << endl;
cout << " b inital: " << b0 << endl;
cout << " b final: " << b << endl;
return 0;
}
counter是int类型的,但是它里面有很多相加的值,这些值可能都大于int。要不试试int64?
您可以硬编码一些测试用例,如n = 20, a =" xyz…",b =" abc…",并将打印语句添加到排序函数中以跟踪正在发生的事情。此外,添加一些注释来澄清不同循环的目的可能会有所帮助。
相关文章:
- C++程序工作,但 Windows 显示"程序.exe已停止工作"
- 程序 使用链表插入数据时停止工作
- 当我尝试输入时程序停止工作
- 由于程序停止工作,生成大量数字失败
- 该程序在执行时停止工作.我在代码块中制作了这个程序
- 为什么我的程序在输入main()之前停止工作
- C++程序在 freopen 中读取大文本后停止工作
- 无限循环使程序停止工作
- 当运行程序时,它说程序.exe停止工作
- 我的程序在执行期间停止工作
- 程序在尝试将 file.read() 文件() 到新变量时停止工作
- 为什么这是为了使程序停止工作?(C )
- 我的C 程序已经停止工作
- 快速排序程序停止工作
- C++程序已停止工作
- 程序停止工作由 strcat() 与指针
- 在 Cout << "hello" << endl 中删除 endl 后,我的C++程序停止工作
- C++使用Qt库的应用程序在屏幕保护程序启动时停止工作
- 制作大桌子时程序停止工作 (2'000'000+)
- 从文件 C++ 程序读取停止工作