c++ - Sort a deque containing struct -


i want sort deque according int g value contained in node struct. structure of program this:

struct node {     int x;     int y;     int g;   };  deque<node> open; 

this sorting function trying 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; } 

in code, go out of bounds when j iterates upto size - 1, results in j+1 being equal size out of bounds.

you can use std::sort inbuilt c++ function.

the syntax std::sort(t.begin(), t.end()) t object want sort.

since using struct, have define ordering, i.e. how less , equal calculated. can either overload inbuilt operators, or define new function , pass third parameter sort function.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -