Yur*_*ury 14 c++ sorting vector stdvector c++11
假设我有一个整数向量:
std::vector<int> indices;
for (int i=0; i<15; i++) indices.push_back(i);
Run Code Online (Sandbox Code Playgroud)
然后我按降序排序:
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]);
Run Code Online (Sandbox Code Playgroud)
这会产生以下结果:
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
Run Code Online (Sandbox Code Playgroud)
现在我想将数字 3、4、5 和 6 移到最后,并保持它们的降序(最好不必sort第二次使用)。即,这是我想要的:
14
13
12
11
10
9
8
7
2
1
0
6
5
4
3
Run Code Online (Sandbox Code Playgroud)
我应该如何修改 的比较功能std::sort来实现这一点?
你比较函数,因为你得到的值错误first和second是的元素std::vector。因此,没有必要将它们用作索引。所以,你需要改变
return indices[first] > indices[second];
Run Code Online (Sandbox Code Playgroud)
到
return first > second;
Run Code Online (Sandbox Code Playgroud)
现在,关于你试图解决的问题......
您可以将 3、4、5 和 6 与其他元素不进行比较,而仍然相互比较:
return indices[first] > indices[second];
Run Code Online (Sandbox Code Playgroud)
从功能标准算法库一样iota,sort,find,rotate并copy会使你的生活更轻松。你的例子归结为:
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
14
13
12
11
10
9
8
7
2
1
0
6
5
4
3
Run Code Online (Sandbox Code Playgroud)
auto a = std::lower_bound(indices.begin(), indices.end(), 6, std::greater<int>{});
auto b = a + 4;
Run Code Online (Sandbox Code Playgroud)