C++ 如何在类内泛化方法
我有一个名为C++ 如何在类内泛化方法,c++,templates,C++,Templates,我有一个名为MinPQ(优先级队列)的类,它处理名为Item的通用数据。除了greater()方法外,其他方法正在对项的索引进行处理。 greater()方法正在比较两个不同的项目-请参见下文。 此方法适用于任何标准数据类型(Item=int,float,等等),但是用户定义的对象呢 如何修改这个MinPQ类和greater()方法以考虑更一般的对象 MinPQ类: template <class Item> class MinPQ { private: Item *item
MinPQ
(优先级队列)的类,它处理名为Item
的通用数据。除了greater()
方法外,其他方法正在对项的索引进行处理。
greater()
方法正在比较两个不同的项目-请参见下文。
此方法适用于任何标准数据类型(Item
=int
,float
,等等),但是用户定义的对象呢
如何修改这个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();
};
有了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 >
有了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 >
有了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 >
有了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 >
你基本上想像比较整数一样比较两个Item
类型的元素吗?为什么不使用std::vector
来存储可变长度的缓冲区?你基本上想像比较整数一样比较两个Item
类型的元素吗?为什么不使用std::vector
来存储你的数据可变长度缓冲区?您基本上想像比较整数一样比较Item
类型的两个元素吗?为什么不使用std::vector
存储可变长度缓冲区?您基本上想像比较整数一样比较Item
类型的两个元素吗?为什么不使用std::vector
来存储可变长度缓冲区?+1,但只需将Item
更改为其他名称,如SomeItem
。由于模板中使用了Item
,因此Item
也可以重载操作符>
+1,但只需将Item
更改为其他名称,如SomeItem
。由于模板中使用了Item
,因此Item
也可以重载操作符>
+1,但只需将Item
更改为其他名称,如SomeItem
。由于模板中使用了Item
,因此Item
也可以重载操作符>
+1,但只需将Item
更改为其他名称,如SomeItem
。由于模板中使用了Item
,因此Item
也会使操作员过载>