我得到了:
"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;
}
我得到了一些函数,它适用于对象,
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()));
}
问题描述:我实现了operator<
和operator==
,通过m_number
执行两个实例的比较,但当集合detectedObjects
和trackedObjects
包含具有相同m_number
的元素时,std::set_difference
返回所有元素,而不是预期的空结果集。
我甚至试图给集合一个函数对象compare
作为模板参数,但结果我得到了很多关于=
和!=
没有正确定义的编译器错误。
我想知道出了什么问题?
我看不出为什么要存储指向对象的指针而不是对象本身。
要使用比较器,您需要确保为所有的集合实例和到set_difference
:提供相同的比较器类型
set<Compound_object*, compare> m_trackedObjects;
set<Compound_object*, compare> detectedObjects;
set<Compound_object*, compare> deleteFromTrackedObjects;
set_difference(detectedObjects.begin(), detectedObjects.end(),
this->m_trackedObjects.begin(), this->m_trackedObjects.end(),
inserter(addToTrackedObjects, addToTrackedObjects.end()),
compare());