簡體   English   中英

PriorityQueue 包含數組 C#

[英]PriorityQueue containing array C#

我想創建一個 PriorityQueue 來存儲 int[]。 數組中的第一個元素將是比較的標准。

我可以在 Java 中輕松做到這一點,盡管我無法將其轉換為 C#。 你能指導我嗎?

在此處輸入圖像描述

優先級隊列在兩種語言中的工作方式不同。 你想要做的是給 PQ 一個 lambda (函數)來比較任何兩個元素的 Java 方式。 在 C# 中,您在將每個元素添加到隊列時給它一個優先級,然后制作一個比較器來比較不同的優先級。

PriorityQueue<int[], int> pq = new(Comparer<int>.Create((a, b) => a - b));
// The Comparer compares the *priorities*, not the elements

pq.Enqueue(new int[] { 1, 2, 3, 4 }, 5);
pq.Enqueue(new int[] { 1, 2, 3, 4 }, 0); // This has more priority
while (pq.TryDequeue(out int[]? arr, out int priority))
{
    Console.WriteLine(priority); // 0; 5
}

您可能只對一個簡單的 List 和 LINQ 感興趣:

using System.Linq; // at the top of your code to include LINQ


List<int[]> list = new();
list.Add(new int[] { 1, 2, 3, 4 });
list.Add(new int[] { 5, 2, 3, 4 });
IEnumerable<int[]> ordered = list.OrderBy(x => x[0]); // orders by the first element

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM