0
我试着写一个程序,在输出字典顺序数字字符串的下一个排列,但我得到一个内存错误:内存问题,不知道为什么。什么()的std :: bad_alloc的
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;
}
当新失败时会抛出'std :: bad_alloc'。我会看看什么'limit'设置为。使用阶乘作为数组限制可以非常快地耗尽内存。 –
1.修复代码缩进。 2.附加一个调试器并查看异常来自哪里。 –
为了清楚起见,我会用矢量替换'vector *',花了我一些时间才意识到这不是一个错字/错误。 –