如何在类中泛化方法
How to generalize a method inside a class
我有一个名为MinPQ
(优先级队列(的类,它适用于名为Item
的通用数据。在greater()
方法之外,其他方法正在对items
的索引执行工作。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();
};
构造函数:
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;
}
};
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 如何在类中泛化方法
- 泛化一个函数,该函数返回基于对象和类方法的可调用函数