Sorting a vector in descending order within two ranges
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;
}
);
Demo
Functions from the standard algorithms library like iota
, sort
, find
, rotate
and copy
would make your life easier. Your example comes down to:
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> indices(15);
std::iota(indices.begin(), indices.end(), 0);
std::sort(indices.begin(), indices.end(), std::greater<>());
auto a = std::find(indices.begin(), indices.end(), 6);
auto b = std::find(indices.begin(), indices.end(), 3);
std::rotate(a, b + 1, indices.end());
std::copy(indices.begin(), indices.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
Output:
14
13
12
11
10
9
8
7
2
1
0
6
5
4
3
@TedLyngmo in the comments makes the good point that it could/should be improved with:
auto a = std::lower_bound(indices.begin(), indices.end(), 6, std::greater<int>{});
auto b = a + 4;