我试图将 powerset 写入文件,但如果我的起始数组大于大小 6,我会得到堆损坏,我不知道为什么。它适用于任何大小的数组 6 或以下。想不通这个。
此外, test.txt 是我在数组中读取的位置。如果文件包含“1,2,3,4,5,6”它工作正常,但它包含“1,2,3,4,5,6,7”我得到堆损坏。
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include "N26.h"
#include <math.h>
using namespace std;
void increaseArray(int* theArray, int size)
{
int i = size;
int n = i+1;
int* newArray = new int[n];
for(int cnt=0;cnt<n;cnt++)
{
newArray[cnt] = theArray[cnt];
}
newArray[n-1]= NULL;
theArray = newArray;
return;
}
void printPowerSet(int *s, int n)
{
int i=0,j=0;
ofstream myFile;
double SetSize=pow(2.0,n);
myFile.open("powerset1.txt", std::ios_base::app);
cout<<"{size of original}"<< n <<endl;
cout<<"{number of sets}"<< SetSize-1 <<endl;
for(i=1;i<SetSize;++i)
{
for(j=0;j<n;++j)
{
if(((i>>j)&1)==1)
{
myFile << s[j] <<",";
}
}
myFile<<endl;
}
return;
}
int main()
{
ifstream myFile;
int item;
string input ="";
string fileName = "test.txt";
myFile.open(fileName);
while(myFile)
{
int k = 1;
int* transaction= new int[1];
if(!getline(myFile,input))
break;
istringstream ss(input);
while(ss)
{
if(!getline(ss,input, ','))
break;
input.erase(remove_if(input.begin(), input.end(), isspace), input.end());
item = atoi(input.c_str());
transaction[k-1] = item;
increaseArray(transaction,k);
k++;
}
for(int i =0; i<k-1;i++)
{
cout << transaction[i];
}
printPowerSet(transaction, k-1);
cout << endl;
transaction=NULL;
}
system("Pause");
return 0;
}