问题描述:

I have the following class

public class MinPQ<T> : IComparable<T>

{

private T[] keys;

...

}

How to implement CompareTo method? I would like to do the following in my method

public void decreaseKey(int i, T key){

if (keys[i].CompareTo(key) <= 0) {...} // or if(CompareTo(keys[i], key) <= 0)

}

Most of the time T will be int or double

网友答案:

I assume that you mean how to declare the type T as comparable. If so, you can do it with the following generic constraint.

public class MinPQ<T> where T: IComparable<T>
{
    private T[] keys;
    ...
}
相关阅读:
Top