+ 2

Issue on Set with custom class

Hi I tried to create a set storing objects of custom class. Below is the code for same: https://code.sololearn.com/cpsm6QpT8WYL Can anyone please help me understand why size is not 2 once I called freqStack.getSize() in main function? I was expecting size as 3 as I am pushing three distinct values those are 5,7 and 4.

19th Mar 2022, 8:49 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Réponses
+ 2
std::set doesn't insert value which are equivalent to any other value in the set. According to cppreference doc on standard set : "two objects a and b are considered equivalent if neither compares less than the other: !comp(a, b) && !comp(b, a)" ( https://en.cppreference.com/w/cpp/container/set ) The comparison operator overload of your *myData* structure would always return "false" when 2 objects with unequal sized "indexes" are compared making them equivalant. For example : Consider the following case where you are trying to insert "a = myData (5, {1,3})" in *pq* and *pq* contains only one entry which is "b"( b.val = 7, and b.indexes = {2}) Due to the fact that a.indexes.size () != b.indexes.size (), neither would (a<b) hold nor (b<a), making *a* and *b* equivalent. And hence *a* would never be inserted in *pq*.
20th Mar 2022, 2:09 AM
Arsenic
Arsenic - avatar
+ 1
Thanks Arsenic. My < operator function's first condition is as below: if (indexes.size() != obj.indexes.size()) return (indexes.size() == obj.indexes.size()); it should have been if (indexes.size() != obj.indexes.size()) return (indexes.size() > obj.indexes.size()); modified code and hence kept both wrong and correct condition so that later on can recognise what was error
20th Mar 2022, 9:24 AM
Ketan Lalcheta
Ketan Lalcheta - avatar