gpt4 book ai didi

c# - 如何在 C# 泛型容器中实现 less 和 greater than?

转载 作者:行者123 更新时间:2023-11-30 19:44:55 24 4
gpt4 key购买 nike

在 C++ 中,使用优先级队列我可以这样写:

priority_queue<int, vector<int>, greater<int>> min_pq;
priority_queue<int, vector<int>, less<int>> max_pq;

我想知道在 C# 容器中是否有等效的方法?我正在实现一个优先级队列,当用户使用其构造函数时,我需要一种方法来指定此行为。我可以使用 boolean 标志,但我觉得它不合适。有什么想法吗?

public class PriorityQueue<T> where T : IComparable<T> {
private List<T> data;

/// <summary>
///
/// </summary>
/// <param name="item"></param>
public void Push(T item) {

}

/// <summary>
///
/// </summary>
public void Pop() {

}
}

最佳答案

C# 中的惯用解决方案是传递 IComparer<T> 的实例到泛型类的构造函数。

public class PriorityQueue<T> {
private readonly IComparer<T> comparer;
public PriorityQueue(IComparer<T> comp = null) {
comparer = comp ?? Comparer<T>.Default;
}
}

关于c# - 如何在 C# 泛型容器中实现 less 和 greater than?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11595950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com