c++程序停止工作

C++ - program has stopped working

本文关键字:停止工作 程序 c++      更新时间:2023-10-16

我下面发布的代码应该在递归(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…",并将打印语句添加到排序函数中以跟踪正在发生的事情。此外,添加一些注释来澄清不同循环的目的可能会有所帮助。