如何在类中泛化方法

How to generalize a method inside a class

本文关键字:泛化 方法      更新时间:2023-10-16

我有一个名为MinPQ(优先级队列(的类,它适用于名为Item的通用数据。在greater()方法之外,其他方法正在对items的索引执行工作。greater()方法是比较两个不同的项目 - 见下文。此方法适用于任何标准数据类型(Item = intfloat 等(,但是用户定义的对象呢?

如何修改此MinPQ类和greater()方法以考虑更通用的对象?

MinPQ类:

template <class Item> class MinPQ
{
private:
    Item *items;
    int N;
    int queueSize;
    void resize(int capacity);
    void swim(int k);
    bool greater(int i, int j);
    void exch(int i, int j);
    void sink(int k);    
public:
    MinPQ();
    MinPQ(const MinPQ &pq);//copy constructor
    ~MinPQ();
    void insert(Item item);
    Item min();
    inline int size(){return N-1;}
    inline bool isEmpty(){return size() == 0;}
    void print();
};

构造函数:

template <class Item> MinPQ<Item>::MinPQ(const MinPQ &pq)
{
    N = pq.N;
    queueSize = pq.queueSize;
    items = new Item[queueSize];
    for(int i = 0; i < N; ++i)
        items[i] = pq.items[i];
}
template <class Item> MinPQ<Item>::MinPQ()
{
    queueSize = 2;
    items = new Item[queueSize];
    N = 1;
}

greater()方法:

template <class Item> bool MinPQ<Item>::greater(int i, int j)
{
    return items[i] > items[j];
}

有了SomeItem的定义,您可以指定运算符>将处理两个项目:

struct SomeItem
{
    //item stuff
    int item_property;
};
bool operator > (const SomeItem & a,const SomeItem & b)
{
    return a.item_property > b.item_property;
}
//after this you can compare items based on item_property.
//...
MinPQ<SomeItem> a;
a.greather(0,1);//this will work as long as types used int MinPQ will have operator >

或者,可以直接在类型中重载运算符:

struct SomeItem
{
    //item stuff
    int item_property;
    bool operator > (const SomeItem & other)const
    {
        return item_property > other.item_property;
    }
};