You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.3 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
void print() {
for (int i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
}
int main() {
// 将数组中一段234位置与56互换
// 学习一下常见的移动元素的策略,实现了将序列右移的目的。
int st = 1; // 开始下标
int ed = 5; // 结束下标 len=(ed-st+1),共(5-1+1)=5个
int len = 3; // 前半段串的长度
//(1)将234反转
reverse(a + st, a + st + len); // 参数:开始的数组索引,开始数组索引+要翻转的长度,这是一个前闭后开的区间[)
print();
//(2)将56反转
reverse(a + st + len, a + ed + 1); // 时刻注意前闭后开
print();
//(3)将23456反转
reverse(a + st, a + ed + 1); // 整个区间翻转,就实现了两个子串互换位置的目标
print();
// 输出1 5 6 2 3 4 7 8 9 10
// 与预期结果一致
puts("");
// 尝试再反转回来
// 后串长度:
reverse(a + st, a + ed + 1 - len);
print();
reverse(a + ed - len + 1, a + ed + 1);
print();
reverse(a + st, a + ed + 1);
print();
// 输出1 2 3 4 5 6 7 8 9 10
// 与预期结果一致
return 0;
}