-4

I have some C++ code like this:

std::vector<PathNode> nodes;


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

Now I will rewrite these C++ code to C#, how can I implement the std::push_heap method?

Yan Chen
  • 45
  • 1
  • 7
  • 2
    `PathNode node = new PathNode();` That's not C++. – DimChtz Jun 03 '18 at 14:13
  • 3
    Why exactly do you need to explicitly convert each individual line of code from one language to another? What makes sense in one language doesn't always make sense in another. Step back and look at the overall functionality of your application. What logic do you need the application to perform? – David Jun 03 '18 at 14:19
  • oh, sorry! I edited my question. – Yan Chen Jun 03 '18 at 14:19
  • this is a pathfinding method from WarZone2100 [link](https://github.com/Warzone2100/warzone2100/blob/master/src/astar.cpp , fpathNewNode method) , I'll tring to rewrite the A* code to C#. – Yan Chen Jun 03 '18 at 14:25
  • I didn't even know of the concept of *heap*. Very interesting. – xanatos Jun 03 '18 at 14:35
  • There is no min/max heap "ordering" plus ancillary methods in the .NET . You'll have to build them or find a library. – xanatos Jun 03 '18 at 14:39

2 Answers2

1

You need to write your own comparison function for the 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()));

For C#

You could use SortedList or a SortedDictionary with a custom key. If you used a type with referential equality, but could be compared based on the value you care about, then this could work.

Heap class in .NET

xanatos
  • 102,557
  • 10
  • 176
  • 249
Ahmed Saleh
  • 1,934
  • 1
  • 29
  • 65
0

I used a general List<>, sorted when Insert:

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;

}
Yan Chen
  • 45
  • 1
  • 7