Yury :
Say I have a vector of integers:
std::vector<int> indices;
for (int i=0; i<15; i++) indices.push_back(i);
Then I sort it in descending order:
sort(indices.begin(), indices.end(), [](int first, int second) -> bool{return indices[first] > indices[second];})
for (int i=0; i<15; i++) printf("%i\n", indices[i]);
This produces the following:
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
Now I want to have the numbers 3, 4, 5, and 6 to be moved to the end, and keep the descending order for them (preferably without having to use sort
for the second time). I.e., here is what I want:
14
13
12
11
10
9
8
7
2
1
0
6
5
4
3
How should I modify the comparison function of the std::sort
to achieve that?
NutCracker :
Your comparison function is wrong since the values you get as first
and second
are the elements of the std::vector
. Therefore, there is no need to use them as indices. So, you need to change
return indices[first] > indices[second];
to
return first > second;
Now, regarding the problem you try to solve...
You can leave 3, 4, 5 and 6 out of comparison with other elements and still compare it with each other:
std::sort(
indices.begin(), indices.end(),
[](int first, int second) -> bool {
bool first_special = first >= 3 && first <= 6;
bool second_special = second >= 3 && second <= 6;
if (first_special != second_special)
return second_special;
else
return first > second;
}
);