变序型算法
变序型算法是通过元素值的赋值和互换,改变元素顺序,但不改变元素值。
//对于每个测试函数, 导入以下头文件
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
reverse():将指定区间元素逆转
int main()
{
vector<int> a{ 1,2,3,4,5,6,7,8,9};
reverse(begin(a), a.end());
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
cout << endl;
reverse(begin(a), a.begin()+4);
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}
reverse_copy():将指定区间元素逆转,转移到目标容器
int main()
{
vector<int> a{ 1,2,3,4,5,6,7,8,9},b;
reverse_copy(begin(a), a.end(),back_inserter(b));
for_each(b.begin(), b.end(), [](int i) {cout << i << ' '; });
cout << endl;
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}
rotate():旋转元素次序
int main()
{
vector<int> a{ 1,2,3,4,5,6,7,8,9},b = a;
rotate(a.begin(),a.begin()+3,a.end()); //可以理解中间为原地修改的起始位。
rotate(b.begin(), b.end() -3, b.end());
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
cout << endl;
for_each(b.begin(), b.end(), [](int i) {cout << i << ' '; });
}
rotate_copy():旋转元素次序,存放于指定容器
int main()
{
vector<int> a{ 1,2,3,4,5,6,7,8,9},b;
rotate_copy(a.begin(),a.begin()+3,a.end(), back_inserter(b));
for_each(b.begin(), b.end(), [](int i) {cout << i << ' '; });
cout << endl;
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}
shuffle():打乱元素次序 (洗牌算法) 每次生成的不同
以时间作为随机数种子
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock
int main()
{
vector<int> a{ 1,2,3,4,5,6,7,8,9};
// obtain a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
shuffle(a.begin(), a.end(), std::default_random_engine(seed)); //需要一个随机数生成函数
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}
内置生成器
#include <random>
int main()
{
vector<int> a{ 1,2,3,4,5,6,7,8,9};
std::random_device rd;
shuffle(a.begin(), a.end(), rd);
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}
random_shuffle():打乱元素次序
不设置种子,每次随机生成的相同
int main()
{
vector<int> a{ 1,2,3,4,5,6,7,8,9};
random_shuffle(a.begin(), a.end());
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}
以时间为种子,就不同了
#include<time.h>
int main()
{
vector<int> a{ 1,2,3,4,5,6,7,8,9};
srand((unsigned)time(NULL));
random_shuffle(a.begin(), a.end());
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}