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?
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?
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.
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;
}