The problem is (see output), obj2 elements look like union of obj2 as passed in main method and obj1. also why do both obj1 and obj2 always start with 1,2 no matter what no. of and what elements are present in them. I have now spent an entire night on this question, it had other problems previously : In C++ program which passes array in constructor, execution stops Howsoever trivial this question may look to you. I would appreciate any help..please..and instead of suggesting complex yet efficient solutions available in library of c++, please try to suggest where i am going wrong as a novice :/
thanks in anticipation!
//partial "integerset.h"
class IntegerSet{
public :
IntegerSet( int [] );
void insertEl(int);
void deleteEl(int); //delete is a keyword, can't be identifier
void printSet();
private :
int setArr[20];//no.s can be 1 to 20
};
//partial "integerset.cpp"
//libraries included
IntegerSet :: IntegerSet( int arr[] ){
for(int i = 0; i < 20; i++)
setArr[i] = 0; //for consistent data at start,avoid garbage
for( int i = 0; i < 20; i++){
if ( arr[i] >= 1 && arr[i] <= 20)
this->insertEl(arr[i]);
}
}
void IntegerSet :: insertEl(int item){
if ( setArr[item-1] != 1) //-1 so that 5 is checked at 4th position, etc.
setArr[item-1] = 1; //set 4th array element to 1 if item = 5
}
void IntegerSet :: deleteEl(int item){ //delete is a keyword, can't be identifier
if ( setArr[item-1] != 0 )
setArr[item-1] = 0;
}
void IntegerSet :: printSet(){
for ( int i = 0; i < 20; i++){
if( this->setArr[i] == 1)
cout<<i+1<<" "; // + 1 important so that 2 displayed at 1st position
}
}
//partial "main.cpp"
int main(){
int a[] = {9,10,15,18,19};
int b[] = {1,3,12,14,15};
IntegerSet obj1(a);
IntegerSet obj2(b);
cout<<"\nintial obj1\n";
obj1.printSet();
cout<<"\ninitial obj2\n";
obj2.printSet();
obj1.deleteEl(18);
cout<<"\nafter deletion of 18 \n";
obj1.printSet();
obj1.insertEl(7);
cout<<"\nafter insertion of 7\n";
obj1.printSet();
system("PAUSE");
return EXIT_SUCCESS;
}
//here's the output
![output of program][1]
http://tinypic.com/view.php?pic=25uiceo&s=5