我正在尝试编写一个程序,以字典顺序输出数字字符串的下一个排列,但是我收到了内存错误:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted
我以前从未遇到过这个问题,有什么想法吗?这是完整的程序:
#include<iostream>
#include<vector>
using namespace std;
vector<char> Next_Permutation(vector<char> InList);
void Reverse_Tail(vector<char>& List,int k);
vector<char> Swap(vector<char> InputList,int k, int l);
vector<char> GetInput();
int Find_K(vector<char> List);
int Find_l(vector<char> List,int k);
int Factorial(int n);
int main(){
vector<char> Input = GetInput();//Getting initial input use 1234 for test
int limit = Factorial(Input.size()); // finds how many permutations will be made
vector<char>* AllPerms = new vector<char>[limit]; //AllPerms is the collection of all permutations(it is an array of vectors where each vector is a permutation)
AllPerms[0] = Input; //setting intial permutation;
for(int i=1;i<2;i++){
// here is where i believe the program crashes. I've tried test = Next_Permutation(AllPerms[i-1]) then
// doing AllPerms[i] = Test and the program runs through the first line fine but crashed on AllPerms[i] = Test?
AllPerms[i] = (Next_Permutation(AllPerms[i-1]));
}
for(int j=0; j < limit;j++){
for(int i=0;i<AllPerms[j].size();i++){
cout << AllPerms[j][i] << " " ;
}
cout << endl;
}
//cout << endl << "K = " << K << endl<< "l = " << l << endl<< endl;
cout << endl<< endl;
return 0;
}
int Factorial(int n){
if(n==0)
return 1;
else
return n*Factorial(n-1);
}
vector<char> Next_Permutation(vector<char> InList){
int K = Find_K(InList);
int l = Find_l(InList,K);
vector<char> Output = Swap(InList,K,l);
Reverse_Tail(Output,K);
}
void Reverse_Tail(vector<char>& List,int k){
int i = k+1;
int lim = (List.size() - i)/2;
int len = List.size()-1;
while(i < (List.size() - lim -1)){
List = Swap(List,i,len);
len--;
i++;
}
}
vector<char> Swap(vector<char> InputList,int k, int l){
vector<char> OutList = InputList;
int Temp = OutList[l];
OutList[l] = InputList[k];
OutList[k] = Temp;
return OutList;
}
int Find_l(vector<char> List,int k){
int l=List.size()-1;
while(List[l] < List[k]){
l--;
}
return l;
}
int Find_K(vector<char> List){
int k = List.size()-2;
while(List[k] > List[k+1]){
k--;
}
if(k == List.size()-1){
return -1;
}
return k;
}
vector<char> GetInput(){
vector<char> InputString;
cout << "Please input the string of symbols you would like to gain all permutations of: ";
char temp = 0 ;
while( temp != '\n' ){
cin.get(temp);
InputString.push_back(temp);
}
InputString.pop_back();
return InputString;
}
答案 0 :(得分:2)
您不会从Next_Permutation
返回值。无法从任何函数返回值,但main
调用未定义的行为,其中编译器和程序可以自由地执行任何他们喜欢的操作。我的Solaris编译器拒绝接受该程序,而我的Linux编译器编译程序,但程序崩溃,因为free
在某个时刻检测到无效指针。两者都是处理未定义事物的有效方法。
当你有不确定的行为时,通常不明智地弄清楚你的程序行为奇怪的原因,因为你看到的任何东西都不一定可以被其他人复制,甚至可能不被您的。确保您有一个有效的程序,然后开始调试。虽然你可能合法地耗尽了内存,但是在尝试复制甚至不是有效对象的东西时,更有可能抛出异常。
您的编译器可能提供了一些诊断,但您可能必须在运行它时请求它们。如果您正在使用g ++,请确保包含-Wall
选项,该选项启用“所有”警告。 (有一些模糊的未启用,但您通常不需要担心它们。)