c++ I have a class that has an array of size 100. However, this 100 might not be
ID: 3850356 • Letter: C
Question
c++
I have a class that has an array of size 100. However, this 100 might not be used entirely, so I have a variable called size that would keep track of number of elements in each object I declare of type Myclass. I need to overload the equality operator(==) through a function that will compare two objects of type Myclass and return true if they are equal. In other words, all elements of array of object one are there in object two with same size of elements for both. The order of the elements doesn't matter.
so if these two objects have the following values in the arrays:
s1: 1 2 4 5
hence size of this is 4
s2: 5 4 2 1
also the size is 4
now the overlaoding function should return true if I type this code:
s1==s2
sample of my class:
class Myclass {
int set[100];
int size;
};
I don't need a full class and code.. just a code that implements overloading the == operator
Explanation / Answer
class Myclass{
int set[100];
int size;
pubic:
bool operator ==(Mycalss c1){ //create method to override operator
if(this.size==c1.size){ //chech size of both object . if not equal , it will not proceed further
sort(this.set,this.set+size); //sort both the arrays
sort(c1.set,c1.set+size);
for(i=0;i<size;++i){ //now check all elements are present of not
if(this.set[i]!=c1.set[i])
return false; // as they are in sorted order, if element does not match return false.
}
return true; //if it reach here it means al elements are present , so return true.
}
}
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.