I got:
“object.h”
namespace objectNS
{
class object
{
public:
int m_number;
bool operator== (const object& object) const;
bool operator< (const object& object) const;
};
class compare
{
public:
bool operator ()(const object*, const object*) const;
};
}
“object.cpp”
#include "object.h"
typedef objectNS::object OBJECT;
bool OBJECT::operator== (const object &object) const
{
return this->m_number == object.m_number;
}
bool OBJECT::operator< (const object &object) const
{
return this->m_number < object.m_number;
}
bool objectNS::compare::operator() (const object* obj1, const object* obj2) const
{
return obj1->m_number > obj2->m_number;
}
I got some function which works with objects,
void f(void)
{
set<Compound_object*> detectedObjects;
set<Compound_object*> deleteFromTrackedObjects;
set_difference(detectedObjects.begin(), detectedObjects.end(), this->m_trackedObjects.begin(), this->m_trackedObjects.end(), inserter(addToTrackedObjects, addToTrackedObjects.end()));
}
Problem description:
I implemented operator< and operator== by which the comparision of two instances is performed by m_number, but when the sets detectedObjects and trackedObjects contain elements with the same m_number, the std::set_difference returns all elements instead of an empty result set as expected.
I even have tried to give a functional object compare to the set as template argument, but as a result I got a lot of compiler errors about = and != not being properly defined.
I wonder what is the problem?
I can’t see a good reason why you’re storing pointers to objects instead of the objects themselves.
To use a comparator, you need to make sure that you’re providing the same comparator type to all of your set instances and to
set_difference: