Search code examples
c++sortingstdlist

Sort a list after incrementing one element


EDIT: I can't use the sort function. I must do a program that has a list which is a ranking of organisms, each organism has its own ID and the ranking must be sorted decreasingly by number of sons and if two organisms have the same number of sons they are sorted increasingly by their ID. I have made the following algorithm that goes after increasing the number of sons of one organism:

list<pair<int, int> >::iterator it = list.begin();
bool found = false;
int id = (id of the incremented organism)
int sons = (number of sons)
while(not found and it != list.end()) {
   if((*it).first == id) found = true;
   if(found and it != rkg.begin()) {
     --it;
     int prevsons = (*it).first;
     int previd = (*it).second;
     ++it;
     if(prevsons < sons or prevsons == sons and previd > id) {
         it = list.erase(it);
         while(((*it).second < sons or (*it).second == sons and (*it).first > id) and it != list.end) --it;
     list.insert(it, id);
     }
   }
   ++it;
}

but it doesn't work well as when i print the ranking after inserting some organisms it is sometimes badly sorted. I would appreciate your help. I can only use the following operations:

void list.clear();
void list.insert(iterator it, const T& x);
iterator list.erase(iterator it);
void splice(iterator it, list& l);
int size() const;

Sorry if i am expressing myself badly, my native language is not english.


Solution

  • I have finally fixed it, i forgot to increment the iterator before inserting the element adding:

    if(it == list.begin() and not ((*it).second < sons or (*it).second == sons and (*it).first > id) or it != rkg.begin()) ++it;