I want to sort a deque according to the int g value contained in the node struct. The structure of my program is this:
struct node
{
int x;
int y;
int g;
};
deque<node> open;
This is the sorting function I am trying but it gives garbage values. Please guide me:
deque<node> sort(deque<node> t)
{
deque<node>::iterator it;
int size= t.size();
node te;
for(int i=0; i<size; i++)
{
for(int j=0; j<size-i; j++)
{
if(t[j].g < t[j+1].g)
{
te.x = t[j].x;
te.y = t[j].y;
te.g = t[j].g;
t[j].x = t[j+1].x;
t[j].y = t[j+1].y;
t[j].g = t[j+1].g;
t[j+1].x = te.x;
t[j+1].y = te.y;
t[j+1].g = te.g;
}
}
}
for(it=t.begin();it!=t.end();it++)
{
te = *it;
cout<<te.x<<","<<te.y<<","<<te.g<<endl;
}
return t;
}
You are going out of bounds when i == 0: you iterate j up to size - 1 inclusively, but then j + 1 == size.
Anyway, there's much simpler and faster solution - just use std::sort:
std::sort(t.begin(), t.end(), [](const node& a, const node& b) {
return a.g > b.g;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With