C++中的迭代器错误

Iterator error in C++

本文关键字:错误 迭代器 C++      更新时间:2023-10-16

我正在编写一个适配器类,它为使用 set 的优先级队列提供接口。

#include<set>
using namespace std;
template<typename PRIO,typename VALUE >
class Adapter 
{
    //a typedef for a type "item", which acts as a pointer to an element in the queue
    //(item is used below in various methods).
    template<typename PR,typename VAL>
    class Node{
    public:
            PR prio;
            VAL value;
                    Node(PR p,VAL v) : prio(p),value(v) {}
    };
    set< Node<PRIO,VALUE> > queue;
    public:
    typedef typename set< Node<PRIO,VALUE> >::iterator item;
    // inserts a new element
    item insert(const PRIO &prio, const VALUE &value) 
    { 
        Node<PRIO,VALUE> temp(prio,value);
        return (queue.insert(temp)).first;
    }
    // decreases the priority of item to prio
    item decPrio(item& it, const PRIO &prio)     //CHANGED !!!!
    {
        Node<PRIO,VALUE> temp(prio,it->value);
        queue.erase(it);
        it=queue.insert(temp);
    }
    // returns the minimum element
    item findMin() const {return queue.begin();}
};

当我编译代码时,我收到错误,与运算符 = 不匹配 it (decPrio 中的变量)。还有一些与 std::less 相关的错误。怎么了?

在这一行中:

    Node<PRIO,VALUE> temp(prio,item->value);

item是一种类型。 也许你的意思是:

    Node<PRIO,VALUE> temp(prio,it->value);

std::set需要一个比较函数对象来清除重复的对象。此函数对象作为可选的第二个模板参数传递给std::set

struct Foo {
    int x;
};
std::set<Foo> foo_set; // <-- Error: doesn't know how to compare two MyType objects
struct FooCompare {
    bool operator()( const Foo& lhs, const Foo& rhs ) const { 
        return lhs.x < rhs.x;
    }
};
std::set<Foo, FooCompare> foo_set; // <-- Works: set uses FooCompare to compare two Foo objects

默认情况下,此比较函数对象设置为std::less专用于集合的值类型。 std::less依次调用operator<集合的值类型。

struct Foo {
    int x;
    bool operator<( const Foo& rhs ) const {
        return x < rhs.x;
    }
};
std::set<Foo> foo_set; // Works!

这就是您的错误消息出现的地方。您没有为 Node 类定义operator<,C++也无法确定您希望如何比较Node对象。只需向Node类添加operator<即可解决问题。或者,您可以创建一个Node比较函数对象,并将其作为第二个模板参数传递给您的std::set,如上例所示。