簡體   English   中英

C ++中的迭代器錯誤

[英]Iterator error in C++

我正在編寫一個適配器類,它為使用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 ,如上面的示例所示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM