What should be changed in the below code? It shows the following error
ERROR: ld.so: object '/home/bot/funcs.so' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
Error in `/home/bot/dcb7b4b8f54571a4467c2113b7856878': free(): invalid next size (fast): 0x0000000000c350b0
#include <iostream>
using namespace std;
int merge(int *left,int nl,int *right,int nr,int *a)
{
int i=0,j=0,k=0;
while(i<nl && j<nr)
{
if(left[i]<right[j])
{
a[k]=left[i];
i++;
}
else
{
a[k]=right[j];
j++;
}
k++;
}
while(i<nl)
{
a[k]=left[i];
i++;
}
while(j<nr)
{
a[k]=right[j];
j++;
}
}
int mergesort(int *a,int n)
{
if(n<2) return 0;
int mid=n/2;
int *left=new int[mid];
int *right=new int[n-mid];
for(int i=0;i<=mid-1;i++)
{
left[i]=a[i];
}
for(int i=mid;i<=n-1;i++)
{
right[i]=a[i];
}
mergesort(left,mid);
mergesort(right,n-mid);
merge(left,mid,right,n-mid,a);
delete[]left;
delete[]right;
}
int main() {
//code
int a[]={10,7,8,9,4,2,3,6,5,1};
int n=sizeof(a)/sizeof(a[0]);
mergesort(a,n);
for(int i=0;i<10;i++)
{
cout<<a[i]<<"\t";
}
return 0;
}
Fixes noted in comments, seems to be working now. A one time allocation of a temp array either in main or in a helper function would be faster. Using mutually recursive functions (one merges AtoA, the other merges AtoTemp, they call each other), eliminates having to copy data. I can post an example later if wanted. Bottom up merge sort would be slightly faster.
#include <iostream>
using namespace std;
// fix return type to void
void merge(int *left,int nl,int *right,int nr,int *a)
{
int i=0,j=0,k=0;
while(i<nl && j<nr)
{
if(left[i]<right[j])
{
a[k]=left[i];
i++;
}
else
{
a[k]=right[j];
j++;
}
k++;
}
while(i<nl)
{
a[k]=left[i];
i++;
k++; // fix
}
while(j<nr)
{
a[k]=right[j];
j++;
k++; // fix
}
}
// fix return type to void
void mergesort(int *a,int n)
{
if(n<2) return; // fix: change return type to void
int mid=n/2;
int *left=new int[mid];
int *right=new int[n-mid];
for(int i=0;i<=mid-1;i++)
{
left[i]=a[i];
}
for(int i=mid;i<=n-1;i++)
{
right[i-mid]=a[i]; // fix
}
mergesort(left,mid);
mergesort(right,n-mid);
merge(left,mid,right,n-mid,a);
delete[]left;
delete[]right;
}
int main() {
//code
int a[]={10,7,8,9,4,2,3,6,5,1};
int n=sizeof(a)/sizeof(a[0]);
mergesort(a,n);
for(int i=0;i<10;i++)
{
cout<<a[i]<<"\t";
}
cout << endl; // added this not needed
return 0;
}
Cleanup, changed output to not use tabs:
#include <iostream>
#include <iomanip> // for std::setw()
using namespace std;
void merge(int *left,int nl,int *right,int nr,int *a)
{
int i=0,j=0,k=0;
while(i<nl && j<nr)
{
if(left[i]<right[j])
a[k++]=left[i++];
else
a[k++]=right[j++];
}
while(i<nl)
a[k++]=left[i++];
while(j<nr)
a[k++]=right[j++];
}
void mergesort(int *a,int n)
{
if(n<2)
return;
int mid=n/2;
int *left=new int[mid];
int *right=new int[n-mid];
for(int i=0;i<=mid-1;i++)
left[i]=a[i];
for(int i=mid;i<=n-1;i++)
right[i-mid]=a[i];
mergesort(left,mid);
mergesort(right,n-mid);
merge(left,mid,right,n-mid,a);
delete[]left;
delete[]right;
}
int main() {
int a[]={10,7,8,9,4,2,3,6,5,1};
int n=sizeof(a)/sizeof(a[0]);
mergesort(a,n);
for(int i=0;i<10;i++)
cout<<setw(2)<<a[i]<<" "; // 2 digit field output
cout << endl;
return 0;
}
You should use std::vector instead of raw pointer:
typedef std::vector<int> ivector;
void merge( const ivector &l, const ivector &r, ivector &to )
{
ivector_const::iterator il = l.begin();
ivector_const::iterator ir = r.begin();
ivector::iterator ito = to.begin();
while( true ) {
if( il == l.end() ) {
if( ir == r.end() )
return;
*ito++ = *ir++;
} else {
if( ir == r.end() || *il < *ir )
*ito++ = *il++;
else
*ito++ = *ir++;
}
}
}
void mergesort( ivector &v )
{
if(v.size()<2) return;
ivector::iterator imid = v.begin() + v.size() / 2;
ivector left( v.begin(), imid );
ivector right( imid, v.end() );
mergesort(left);
mergesort(right);
merge( left, right, v );
}
int main() {
//code
ivector a ={10,7,8,9,4,2,3,6,5,1};
mergesort(a);
for(size_t i=0;i<a.size();i++)
{
cout<<a[i]<<"\t";
}
return 0;
}
Note: I did not validate your algorithm just rewrote it with std::vector instead of raw pointer. You can notice how simpler your function become when you use proper data type.
Related
I have to make a program with a hash table that maps single random characters into the table. The program kind of works but sometimes it crashes, also it doesn't map every element. Some of them just won't get inside the table and there are always spare spaces in the table. I don't know what to do to solve these 2 problems. I used 3 versions of open adressing and each of them causes the same 2 problems. Sorry for my bad English. Thank you in advance.
Edited. Of course, I forgot about dynamic allocation. But the problem isn't solved.
#include <time.h>
#include <string>
#include <cstdlib>
using namespace std;
int Liniowo(int i, int proby, int rozmiar) // (open adressing, Linear probing)
{
if(i+proby<rozmiar)
return i+proby;
else
{
return -1;
}
}
int Kwadratowo(int i, int proby, int rozmiar) // (open adressing, Quadratic probing)
{
if (i+proby*proby<rozmiar)
return i+proby*proby;
else
{
return -1;
}
}
int Podwojnie(int i, int proby, int rozmiar, char klucz) // (open adressing, Double hashing)
{
if (i*(klucz*(701%klucz)-klucz%13)<rozmiar&&i*(klucz*(701%klucz)-klucz%13)>0)
return i*(klucz*(701%klucz)-klucz%13);
else
{
return -1;
}
}
int modularnie(char c,int rozmiar) // modular
{
return c%rozmiar;
}
void dodaj(char *tab,int max, char c) // add an element
{
int i=modularnie(c, max);
if (tab[i]== '\0')
tab[i]=c;
else
{
int u=0;
int h;
while (tab[i]!= '\0'&&h!=-1)
{
u++;
// h=Kwadratowo(i, u, max);
h=Podwojnie(i,u,max,c);
}
if (h!=-1)
tab[h]=c;
else
cout << "no niestety, nie udalo sie wstawic " <<endl; //"I couldn't map the element"
}
}
int wyszukaj(char *tab,int max, char c) // search an element
{
int i=modularnie(c, max);
int j=i;
if (tab[i]== '\0')
return -1;
while (tab[i]==c)
{
i=(i+1)%max;
if((i==j)||(tab[i]== '\0'))
return -1;
}
return i;
}
int usun(char *tab,int max, char c) // remove an element
{
int r,j,i=wyszukaj(tab,max,c);
j=i;
if (i==-1)
return -1;
tab[i]= '\0';
while (tab[(++i)%max]!= '\0')
{
i%=max;
r=modularnie(tab[i],max);
if (((i<r)&&(r<=j)) || ((r<=j)&&(j<i)) || ((j<i)&&(i<r)))
{
tab[j]=tab[i];
tab[i]= '\0';
j=i;
continue;
}
}
return 0;
}
int main()
{
srand( time( NULL ) );
int ile;
cout << "podaj wielkosc tablicy: "; //"Type the size of the table"
cin >> ile;
char* tab; // EDITED
tab=new char(ile);
for (int n=0; n<ile; n++)
{
tab[n]= '\0';
}
char e;
for (int i=0; i<ile; i++)
{
e='!'+rand()%127;
dodaj(tab, ile, e);
}
for(int j=0; j<ile; j++)
{
cout << j << ", " << tab[j] << endl;
}
return 0;
}
It's my program to simplify Karnough map. I need to change it from SOP to POS for university project. I changed already signs from + to * and from * to +. All i have to do now is to make it read zero-s from text file instead of one's. i tried everything to solve that problem, but i have no idea. I have got two txt files, one with input and one with output. At this moment i need to put in input 0's instead of 1's and in the other side to, to make it work. Please help me, my life depends of that
#include <iostream>
#include <fstream>
#include <cmath>
#include <windows.h>
using namespace std;
//?????
int pow2(int n) // ??2?????,2^n
{
int result=1
;
while(n>0)
result*=2,n--;
return result;
}
int combination(int n,int r) // ?????C_n^r,? n! / ((n-r)!*(r)!)
{
int fm=1,fz=1;
for(int i=1;i<=r;i++,n--)
{
fm*=i;
fz*=n;
}
return fz/fm;
}
void d2b(int d,char* b,int n) // ???????,??????d???????????b?
{
for(n--;n>=0;n--)
{
b[n]='0'+d%2;
d/=2;
}
}
int ispair(char* a1,char* a2,int n) // ????????????????
{
int x,y=0;
for(int i=0;i<n;i++)
if(a1[i]!=a2[i])
x=i,y++;
if(y==1) return x;
else return-1;
}
bool issame(char* a1,char* a2,int n) // ????
{
for(int i=0;i<n;i++)
if(a1[i]!=a2[i])
return 0;
return 1;
}
int left1(char* a,int N) // ???????????,??????1,??????
{
for(int i=0;i<N;i++)
if(a[i]=='1')
return i;
return -1;
}
void copy(char* a1,char* a2,int n) // ??????
{
for(int i=0;i<n;i++)
a2[i]=a1[i];
}
bool isinside(int x,char* a,int n) // ???x????????a?
{
for(n--;n>=0;n--)
{
if(a[n]!='x' && a[n]!=(char)('0'+x%2))
return 0;
x/=2;
}
return 1;
}
void output(fstream& file,char* a,int n)
{
for(int i=0;i<n;i++)
{
if(i==0)file<<'(';
if(a[i]=='0'||a[i]=='1')
{
if(a[i]=='0') file<<'¬'<<(char)('a'+i);
if(a[i]=='1') file<<(char)('a'+i);
if(a[i+1]=='0'||a[i+1]=='1'||a[i+2]=='0'||a[i+2]=='1'||a[i+3]=='0'||a[i+3]=='1')
{
file<<'+';
}
else{
file<<')';
}
}
else{}
;
}
file<<'*';
}
int count(char* table,char* a,int n,int N) // ??,????????1???????????a?
{
int counter=0;
for(int i=0;i<N;i++)
{
if(table[i]!='1') continue;
if(isinside(i,a,n)) counter++;
}
return counter;
}
void clean(char* table,char* a,int n,int N) // ??????????????????1,???x
{
for(int j=0;j<N;j++)
if(isinside(j,a,n))
table[j]='x';
}
int main()
{
SetConsoleTitle("???-???????????");
system("color 06");
//????
fstream inputFile("input.txt",ios::in); //??????????input.txt
int valNum; //???
inputFile >> valNum; // ???????????
cout<<"\n ????????: "<<valNum;
cout<<"\n ?????????:\n";
int minTermLength=pow2(valNum); // ??????????2^valNum?
char* minTermExpression=new char[minTermLength]; // ???????????????
int lineOff = pow2(ceil(double(valNum)/2));
// ???????
if (inputFile.is_open())
{
for(int i=0;i<minTermLength;i++) // ?????
{
inputFile>>minTermExpression[i];
if(i%lineOff == 0&&(i!=0))
cout<<"\n";
cout<<"\t"<<minTermExpression[i];
}
inputFile.close();
}
// ??????
else{
cout<<"\n ??input.txt??,???????";
return 0;
}
// ?implication????????
char*** implication=new char**[valNum]; // ????
int nonZeroNum=1;
for(int i=0;i<minTermLength;i++)
if(minTermExpression[i]!='0') // ?????ON???DC?????????
nonZeroNum++;
for(int i=0;i<valNum;i++) // i-??,???????3?,i=0???????,i=1???,i=2???
{
if(pow2(i)>nonZeroNum)break;
int x=pow2(i-1)*combination(nonZeroNum,pow2(i));
implication[i]=new char*[x];
for(int j=0;j<x;j++)
implication[i][j]=new char[valNum];
}
//?????????
int* countNum=new int[valNum+1];
countNum[0]=0;
for(int i=0;i<minTermLength;i++)
if(minTermExpression[i]!='0') // ???0?
{
d2b(i,implication[0][countNum[0]],valNum); // ??????????implication[0]???
countNum[0]++;
}
int isOptimal=0;
while(countNum[isOptimal]>0) // ??????????
{
countNum[isOptimal+1]=0;
for(int i=0;i<countNum[isOptimal]-1;i++)
for(int j=i+1;j<countNum[isOptimal];j++)
{
int x=ispair(implication[isOptimal][i],implication[isOptimal][j],valNum); // ??????????
if(x==-1) continue;
copy(implication[isOptimal][i],implication[isOptimal+1][countNum[isOptimal+1]],valNum);// ???implication??
implication[isOptimal+1][countNum[isOptimal+1]][x]='x'; // ??????????,?????????x,???????????
countNum[isOptimal+1]++;
}
for(int i=0;i<countNum[isOptimal+1]-1;i++)
for(int j=i+1;j<countNum[isOptimal+1];j++)
if(issame(implication[isOptimal+1][i],implication[isOptimal+1][j],valNum)) // ??????
{
for(int k=j;k<countNum[isOptimal+1]-1;k++)
copy(implication[isOptimal+1][k+1],implication[isOptimal+1][k],valNum);
countNum[isOptimal+1]--;
}
isOptimal++;
}
isOptimal--;
//???????
fstream outputFile("output.txt",ios::out);
outputFile<<"F=";
while(left1(minTermExpression,minTermLength)>=0) //?minTermExpression???1
{
bool flag=0; // ???,????
for(int i=0;i<minTermLength&&flag==0;i++)
{
if(minTermExpression[i]!='1') continue;
int counter=0,recorder;
for(int j=0;j<countNum[isOptimal];j++)
if(isinside(i,implication[isOptimal][j],valNum))
counter++,recorder=j;
if(counter!=1) continue;
output(outputFile,implication[isOptimal][recorder],valNum);
clean(minTermExpression,implication[isOptimal][recorder],valNum,minTermLength);
flag=1;
}
if(flag==1) continue;
int termMaxInclude=0;
int recorder=0;
for(int i=0;i<countNum[isOptimal];i++) // ??????????,???????????1???,??????
if(count(minTermExpression,implication[isOptimal][i],valNum,minTermLength)>termMaxInclude)
termMaxInclude=count(minTermExpression,implication[isOptimal][i],valNum,minTermLength),recorder=i;
if(termMaxInclude==0) {isOptimal--; continue;}
output(outputFile,implication[isOptimal][recorder],valNum);
clean(minTermExpression,implication[isOptimal][recorder],valNum,minTermLength);
}
outputFile.close();
// ?????
outputFile.open("output.txt",ios::in);
char finalExpression[201];
outputFile.getline(finalExpression,200);
outputFile.close();
int termMaxInclude=0;
for(;finalExpression[termMaxInclude]!='\0';termMaxInclude++);
finalExpression[termMaxInclude-1]='\0';
outputFile.open("output.txt",ios::out);
outputFile<<finalExpression;
outputFile.close();
cout<<"\n??????????????";
cout<<"\n ??????,??????!";
cin.get();
return 0;
}
The zeros are simply those not in the ones list.
in my C++ class we are finally getting conceptually fairly deep (well, relatively!) and I'm struggling with building a class from a previous class.
Here is my first class header, which builds partially filled array objects. To my knowledge, it is fully functional:
#ifndef PARTIALARRAY_H
#define PARTIALARRAY_H
#include <iostream>
#include <string.h>
using namespace std;
typedef int ITEM_TYPE;
ITEM_TYPE const MAX = 50;
class PartialArray
{
public:
//-----------------------------------------ctors:-----------------------------------------
PartialArray();
PartialArray(const int init[], int used);
//-----------------------------------------member functions:-----------------------------------------
void PrintArray();
int Search(ITEM_TYPE key);
int Append(ITEM_TYPE appendMe);
int ShiftRight(int shiftHere);
int ShiftLeft(int shiftHere);
int InsertBefore(ITEM_TYPE insertThis, int insertHere);
int InsertAfter(ITEM_TYPE insertThis, int insertHere);
int Delete(int deleteHere);
void DeleteRepeats();
int NumUsed();
void Sort();
void Reverse();
string ErrorDescr(int failCode);
//-----------------------------------------operators:-----------------------------------------
ITEM_TYPE& operator [] (ITEM_TYPE x);
private:
//-----------------------------------------member vars:-----------------------------------------
ITEM_TYPE a[MAX];
int numUsed;
};
#endif // PARTIALARRAY_H
And here are the class functions:
#include "partialarray.h"
#include <iostream>
#include <string.h>
using namespace std;
//-----------------------------------------ctors:-----------------------------------------
PartialArray::PartialArray()
{
numUsed=0;
}
PartialArray::PartialArray(const int init[], int used)
{
numUsed = used;
for(int i=0; i<numUsed; i++)
{
a[i]=init[i];
}
}
//-----------------------------------------member functions:-----------------------------------------
//Prints the array up to its last used element
void PartialArray::PrintArray()
{
for(int i=0; i<numUsed; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
//Searches the array for a particular value and returns the index at which the value first appears
int PartialArray::Search(ITEM_TYPE key)
{
for(int i=0; i<numUsed; i++)
{
if(a[i]==key)
return i;
}
return -1;
}
//Takes a number and appends it to the end of the array after the last interesting element
int PartialArray::Append(ITEM_TYPE appendMe)
{
if(numUsed<MAX)
a[numUsed++] = appendMe;
else
return 1;
return 0;
}
//Shifts all elements of the array to the right starting at a particular index
int PartialArray::ShiftRight(int shiftHere)
{
if(shiftHere<numUsed)
{
ITEM_TYPE save = a[numUsed-1];
for(int i=numUsed; i>=shiftHere; i--)
{
a[i] = a[i-1];
}
a[shiftHere] = save;
return 0;
}
else
return 2;
}
//Shifts all elements of the array to the left starting at a particular index
int PartialArray::ShiftLeft(int shiftHere)
{
if(shiftHere<numUsed)
{
ITEM_TYPE save = a[shiftHere];
for(int i=shiftHere; i<numUsed; i++)
{
a[i] = a[i+1];
}
a[numUsed-1] = save;
return 0;
}
else
return 2;
}
//Takes a number and a position and inserts the number before that position in the array shifting the elements to the right
int PartialArray::InsertBefore(ITEM_TYPE insertThis, int insertHere)
{
if(insertHere>numUsed)
return 2;
else
{
numUsed++;
ShiftRight(insertHere);
a[insertHere] = insertThis;
}
return 0;
}
//Takes a number and a position and inserts the number after that position in the array shifting the elements to the right
int PartialArray::InsertAfter(ITEM_TYPE insertThis, int insertHere)
{
if(insertHere>numUsed)
return 2;
else if(numUsed>=MAX)
return 1;
else
{
numUsed++;
ShiftRight(insertHere+1);
a[insertHere+1] = insertThis;
}
return 0;
}
//Takes a position and removes that item from the array, shifting all the elements to the left
int PartialArray::Delete(int deleteHere)
{
if(deleteHere <= numUsed)
{
ShiftLeft(deleteHere);
numUsed--;
return 0;
}
else
return 2;
}
//Deletes repeated elements in the array and replaces the with 0
void PartialArray::DeleteRepeats()
{
for(int i=0;i<numUsed;i++)
{
ITEM_TYPE n=a[i];
for(int j=i+1; j<numUsed;j++)
{
if(n == a[j])
{
Delete(j);
j--;
}
}
}
}
//Returns number of interesting elements in the array
int PartialArray::NumUsed()
{
return numUsed;
}
//Utilizes a bubble sort algorithm
void PartialArray::Sort()
{
bool swap = true;
int j = 0;
int save;
while (swap==true)
{
swap = false;
j++;
for (int i = 0; i < numUsed - j; i++)
{
if (a[i] > a[i + 1])
{
save = a[i];
a[i] = a[i + 1];
a[i + 1] = save;
swap = true;
}
}
}
}
void PartialArray::Reverse()
{
for(int i=0;i<numUsed-1;i++)
{
ITEM_TYPE save = a[numUsed-1];
ShiftRight(i);
a[i] = save;
}
}
//Returns the appropriate error description for a particular fail code
string PartialArray::ErrorDescr(int failCode)
{
switch(failCode)
{
case -1:
return "ERROR: item not found";
break;
case 1:
return "ERROR: array is full";
break;
case 2:
return "ERROR: unused index";
break;
default:
return "UNKNOWN ERROR";
break;
}
}
//-----------------------------------------operators:-----------------------------------------
ITEM_TYPE& PartialArray::operator [](ITEM_TYPE x)
{
return a[x];
}
Now, here is where things have gotten tricky. To build the two dimensional array class, I'm supposed to create an array of arrays. I'm at a loss as to how I should go about this, and after tinkering and googling for a few hours I've only become more confused. Specifically, the <<, [], and [](constant version) operators and the TwoDArray constructor have thrown me for a loop, and I'm stuck without much sense of what to do next. Here is the TwoD header file:
#ifndef TWODARRAY_H
#define TWODARRAY_H
#include "partialarray.h"
#include <iostream>
#include <string.h>
typedef int ITEM_TYPE;
class TwoDArray
{
friend ostream& operator << (ostream &outs, const TwoDArray& printMe);
public:
//ctors:
TwoDArray();
//member functions:
//PartialArray& operator [](int index); //[ ] operator for the TwoDArray object
//PartialArray operator [](int index) const; //[ ] operator for the TwoDArray object (const version)
int Append(int appendMe, int row);
int InsertBefore(int insertMe, int row, int column);
int InsertAfter(int insertMe, int row, int column);
int Delete(int row, int column);
bool Search(ITEM_TYPE key, int &row, int &column);
private:
//member vars:
PartialArray a[MAX];
};
#endif // TWODARRAY_H
And this is what I've tried to define thus far:
TwoDArray::TwoDArray()
{
const int array0[]= {0};
PartialArray array(array0, MAX);
}
ostream& operator << (ostream &outs, const TwoDArray& printMe)
{
for(int i=0;i<MAX;i++)
{
outs << printMe.a[i];
}
return outs;
}
Ideally, the << operator will print an m by n array of items.
I'm having an issue with the last function in my code that destroys the array, I keep getting Double free or corruption which I think means I'm freeing it up twice but I can't figure out how i'm doing that
Main Code
#include "terrible_dynamic_size_array_unsorted.h"
using namespace std;
int main()
{
int_array arraytest;
init(arraytest);
if(arraytest.count==0)
{
cout<<"Empty array created"<<endl;
}
else
{
cout<<"Error in array creation"<<endl;
}
clear(arraytest);
if(arraytest.count==0)
{
cout<<"Array cleared of data"<<endl;
}
else
{
cout<<"Error in clear function"<<endl;
}
for(unsigned int i=0;i<25;i+=2)
{
if(arraytest.count < arraytest.DEFAULT_CAPACITY)
{
add(arraytest,i);
print(arraytest);
}
else
{
add(arraytest,i);
print(arraytest);
}
}
for(unsigned int i=1;i<25;i+=2)
{
if(arraytest.count < arraytest.DEFAULT_CAPACITY)
{
add(arraytest,i);
print(arraytest);
}
else
{
add(arraytest,i);
print(arraytest);
}
}
if(arraytest.capacity == 2*arraytest.DEFAULT_CAPACITY)
{
cout<<"Resize function works properly"<<endl;
}
else
{
cout<<"Resize not working properly"<<endl;
}
if(contains(arraytest,6))
{
cout<<"Number 6 present in Array"<<endl;
}
else
{
cout<<"Number 6 not in Array Contains not working properly"<<endl;
}
if(contains(arraytest,30))
{
cout<<"Number 30 present in Array Contains not working properly"<<endl;
}
else
{
cout<<"Number 30 not in Array"<<endl;
}
if(remove(arraytest,23) && arraytest.count == 24)
{
cout<<"Number 23 removed from Array"<<endl;
}
else
{
cout << arraytest.count << endl;
cout<<"Number 23 not in Array error in remove"<<endl;
}
if(remove(arraytest,24) && arraytest.count == 23)
{
cout<<"Number 24 removed from Array"<<endl;
}
else
{
cout<<"Number 24 not in Array error in remove"<<endl;
}
if(remove(arraytest,0) && arraytest.count == 22)
{
cout<<"Number 0 removed from Array"<<endl;
}
else
{
cout<<"Number 0 not in Array error in remove"<<endl;
}
if(remove(arraytest,35))
{
cout<<"Error in remove function"<<endl;
}
else
{
cout<<"Number not in Array"<<endl;
}
destr(arraytest);
if(*arraytest.data == 0)
{
cout<<"Array destroyed"<<endl;
}
else
{
cout<<"Error in destroy"<<endl;
}
return 0;
}
Function code
#include "terrible_dynamic_size_array_unsorted.h"
using namespace std;
void init(int_array& arr)
{
arr.count = 0; //set count to 0
arr.capacity = arr.DEFAULT_CAPACITY;
arr.data = new int[arr.capacity];
}
void clear(int_array& arr)
{
destr(arr); //destroys array
init(arr); // initializes array
}
void destr(int_array& arr) //function for destroying array
{
delete[] arr.data;
//*arr.data = 0;
arr.count = 0;
}
void print(const int_array& arr) //prints out the array
{
for (unsigned int i = 0; i < arr.count; ++i)
cout << arr.data[i] << " ";
cout << endl;
}
bool contains(const int_array& arr, const int& target) //
{
unsigned int i;
for (i = 0; i < arr.count; ++i)
{
if (arr.data[i] == target) return true;
//else return false;
}
return false;
}
void resize(int_array& arr) //resizes the array --- WORKING
{
arr.capacity *= 2;
int* new_data = new int[arr.capacity];
for (unsigned int i = 0; i < arr.count; ++i)
{
new_data[i] = arr.data[i];
}
arr.data = new_data;
delete [] arr.data;
}
void add(int_array& arr, const int& payload)
{
if ((arr.count == arr.capacity))
resize(arr);
arr.data[++arr.count] = payload;
}
bool remove(int_array& arr, const int& target)
{
unsigned int i = 0;
if (arr.count == 0)
{
return false;
}
while (i <= arr.count && arr.data[i] != target) {i++;}
if (i > arr.count)
{
return false;
}
arr.data[i] = arr.data[arr.count];
arr.count--;
return true;
}
Header file
#include <iostream>
struct int_array {
int* data;
unsigned int count;
unsigned int capacity;
static const unsigned int DEFAULT_CAPACITY = 20;
};
void init(int_array& arr);
void destr(int_array& arr);
void resize(int_array& arr);
void clear(int_array& arr);
void add(int_array& arr, const int& payload);
bool contains(const int_array& arr, const int& target);
bool remove(int_array& arr, const int& target);
void print(const int_array& arr);
The problem lies with the function void destr(int_array& arr)
Thank you.
arr.data = new_data;
delete [] arr.data;
should be
delete[] arr.data;
arr.data = new_data;
Or, the old array will be leaked and arr.data will point to already freed memory - which will then be illegally freed again by destr.
why my program Time Limited Error?
because of the sort?
this is the question
link text
#include <cstdio>
#include <cstring>
using namespace std;
int map[22][44];
int book[22];
int total;
int sum;
int way[22];
int tails[22];
int tail;
void init()
{
memset(map,0,sizeof(map));
memset(book,0,sizeof(book));
sum =0;
memset(way,0,sizeof(way));
way[1]=1;
memset(tails,0,sizeof(tails));
}
void sort()
{
int t;
for (int i=1;i<=22;i++)
{
if (tails[i]==0)
break;
else
{
for (int j=1;j<=tails[i]-1;j++)
for (int k=j+1;k<=tails[i];k++)
{
if (map[i][j] > map[i][k])
{
t = map[i][j];
map[i][j]=map[i][k];
map[i][k]=t;
}
}
}
}
}
void dfs(int x,int y)
{
if ((x < 1)||(x > 22))
return;
if (book[x]==1)
return;
//printf("%d \n",x);
if (x == total)
{
sum++;
for (int i=1;i<=y-1;i++)
{
printf("%d ",way[i]);
}
printf("%d",total);
printf("\n");
return;
}
tail = tails[x];
for (int i=1;i<=43;i++)
{
book[x]=1;
way[y]=x;
dfs(map[x][i],y+1);
book[x]=0;
}
}
int main()
{
int temp1,temp2;
//freopen("ex.in","r",stdin);
//freopen("ex.out","w",stdout);
int c = 0;
while(scanf("%d",&total)!=EOF)
{
c++;
printf("CASE ");
printf("%d",c);
printf(":");
printf("\n");
init();
for (;;)
{
scanf("%d%d",&temp1,&temp2);
if ((temp1 == 0)&&(temp2 == 0))
break;
else
{
tails[temp1]++;
tail = tails[temp1];
map[temp1][tail]=temp2;
tails[temp2]++;
tail = tails[temp2];
map[temp2][tail]=temp1;
}
}
sort();
dfs(1,1);
printf("There are ");printf("%d",sum);printf(" routes from the firestation to streetcorner ");printf("%d",total);printf(".");
printf("\n");
}
return 0;
}
Because your sorting algoritm is in worst-case O(n*n), you can use InnoSort for better worst-case complexity O(n*log(n)).
You are using C++ then use sort function from <algorithm> header to do this simplest.
Documentation you can find at http://www.sgi.com/tech/stl/sort.html
For a start, you're accessing tails and map past the end. C++ arrays are zero-indexed, so the first element is 0, and the last valid elements are tails[21] and map[21][43].