使用set_difference算法时找不到错误

时间:2012-08-24 08:55:21

标签: c++ stl operator-overloading set-difference stdset

我得到了:

“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和{{1}时}包含具有相同trackedObjects的元素,m_number返回所有元素,而不是按预期返回空结果。

我甚至试图将一个功能对象std::set_difference赋予set作为模板参数,但结果我得到了很多关于compare=不正确的编译器错误定义

我想知道这是什么问题?

1 个答案:

答案 0 :(得分:2)

我看不出你为什么要存储指向对象的指针而不是对象本身的原因。

要使用比较器,您需要确保为所有 提供与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());