Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector Sort Algorithm, sort only elements bigger then 0

I have to sort a vector of structs. Let's say the struct has two members:

Struct game
{
  string name;
  int rating;
};

So I have created a std::vector<game> games and simple sort them by rating.

std::sort(games.begin(),games.end(), [](game& info1, game& info2)
{
    return info1.rating > info2.rating;
});

Everything is alright so far. The problem is if all games have rating value 0, they mix. Simply put I have to sort only elements with rating bigger than zero. Let's give you an example:

All games are pushed in the vector by names in alphabetic order and rating 0, when a sort is triggered, the alphabet order gets violated.

Example before sort:

"A_Game", "B_Game", "C_Game", "E_Game", "G_Game", etc. (continue with all next letters)

after sort (all games are with rating 0):

"G_Game", "S_Game", "P_Game", "M_Game", "L_Game", "I_Game", etc.

I need to sort only these games that have rating bigger than 0. Thanks in advance.

like image 227
Rosen Karadinev Avatar asked Nov 29 '22 21:11

Rosen Karadinev


1 Answers

You can use std::stable_sort to prevent moving around elements that are not affected by the sorting criteria.

std::stable_sort(games.begin(),games.end(), [](game& info1, game& info2)
{
    return info1.rating > info2.rating;
});
like image 113
Vittorio Romeo Avatar answered Dec 04 '22 15:12

Vittorio Romeo