我在下面发布的代码应该在递归(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;
}
答案 0 :(得分:4)
由于递归过深,调用堆栈可能会溢出?
答案 1 :(得分:1)
要添加到iltal的评论,您可能希望打印出有关字符串a,b的信息:a.size(),a.length(),a.capacity(),a.max_size()
答案 2 :(得分:1)
我不确定这段代码是做什么的。这是一个修订版,添加了一些打印语句,以及一个随机字符串生成器。
#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;
}
答案 3 :(得分:0)
计数器的类型为int,但它有很多值相加,可能都大于int。也许尝试int64?
答案 4 :(得分:0)
您可以对某些测试用例进行硬编码,例如n = 20,a =“xyz ...”,b =“abc ...”,并将print语句添加到sort函数以跟踪正在进行的操作。此外,添加一些注释以阐明不同循环的用途可能会有所帮助。