如何将 C++ std::p ush_heap 转换为 C#?

how can I convert C++ std::push_heap to C#?

本文关键字:heap 转换 C++ std ush      更新时间:2023-10-16

我有一些这样的C++代码:

std::vector<PathNode> nodes;

PathNode node;
....
nodes.push_back(node);
std::push_heap(nodes.begin(), nodes.end());

现在我将把这些C++代码重写为 C#,如何实现 std::p ush_heap 方法?

你需要为 PathNode 编写自己的比较函数

struct greaters{
bool operator()(const PathNode& a,const PathNode& b) const{
return a.x>b.x;
}
};    
std::vector<PathNode> nodes;

PathNode node;
nodes.push_back(node);
std::make_heap(nodes.begin(), nodes.end(), greaters()));
std::push_heap(nodes.begin(), nodes.end(), greaters()));

对于 C#

您可以将SortedListSortedDictionary与自定义密钥一起使用。如果您使用了具有引用相等性的类型,但可以根据您关心的值进行比较,那么这可能会起作用。

.NET 中的堆类

我使用了一个通用列表<>,排序时插入:

static List<int> nodes = new List<int>();
static void Main()
{
PushNode(3);
PushNode(12);
PushNode(4);
PushNode(6);
PushNode(5);
PushNode(8);
PushNode(2);
PushNode(9);
PushNode(1);
foreach (int value in nodes)
{
Console.WriteLine(value);
}
}
static void PushNode(int value)
{
for (int i = 0; i < nodes.Count; i++)
{
if (nodes[i] > value)
{
nodes.Insert(i, value);
return;
}
}
nodes.Add(value);
return;
}