一、STL
算法概述
- 算法主要包含在头文件
<algorithm>
<functional>
<numeric>
中。 <algorithm>
是所有STL头文件中最大的,涉及到:遍历、比较、 查找、交换、复制、修改等操作。<functional>
定义了一些模板类,用来声明函数对象。<numeric>
最小,只包含几个在序列上进行简单数学运算的模板函数。
二、random_shuffle
功能:洗牌,随机调整指定范围内元素的次序
random_shuffle()
算法包含在头文件<algorithm>
中
函数原型: | random_shuffle(iterator beg, iterator end) | 解释 |
---|---|---|
参数1 | iterator beg | 开始迭代器 |
参数2 | iterator end | 结束迭代器 |
参数3(选填) | random | 随机数生成器 |
说明:random_shuffle()
内部使用的随机数生成器,默认为 rand()
。也可以传入自定义的随机数生成器。
示例1: vector随机排序
#include <iostream>
#include <algorithm> //必须包含该头文件
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
void printA(int value)
{
cout << value << " ";
}
void test01()
{
//随机数种子
srand((unsigned)time(NULL));
vector<int> vec;
for (int i = 0; i < 10; i++)
{
vec.push_back(i);
}
cout << "洗牌前:";
for_each(vec.begin(), vec.end(), printA);
cout << endl;
//洗牌(打乱顺序)
random_shuffle(vec.begin(), vec.end());
cout << "洗牌后:";
for_each(vec.begin(), vec.end(), printA);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
//result
洗牌前:0 1 2 3 4 5 6 7 8 9
洗牌后:7 9 3 8 5 0 4 2 1 6
示例2: vector随机排序-自定义随机数生成器
#include <iostream>
#include <algorithm> //必须包含该头文件
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
void printA(int value)
{
cout << value << " ";
}
//自定义随机数生成器
int random(int i)
{
return rand() % i;
}
void test01()
{
//随机数种子
srand((unsigned)time(NULL));
vector<int> vec;
for (int i = 0; i < 10; i++)
{
vec.push_back(i);
}
cout << "洗牌前:";
for_each(vec.begin(), vec.end(), printA);
cout << endl;
//洗牌(打乱顺序)-使用自定义随机数生成器random
random_shuffle(vec.begin(), vec.end(), random);
cout << "洗牌后:";
for_each(vec.begin(), vec.end(), printA);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
//result
洗牌前:0 1 2 3 4 5 6 7 8 9
洗牌后:8 1 9 2 0 5 7 3 4 6
示例3: string随机排序
#include <iostream>
#include <algorithm> //必须包含该头文件
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
void test01()
{
//随机数种子
srand((unsigned)time(NULL));
string str = "ABCDEFGHIJK";
cout << "洗牌前:";
cout << str << endl;
//洗牌(打乱顺序)
random_shuffle(str.begin(), str.end());
cout << "洗牌后:";
cout << str << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
//result
洗牌前:ABCDEFGHIJK
洗牌后:KBJCAFHDEGI
注意:
- 对于
vector
(连续型可任意访问的容器)、string
以及数组都可以使用random_shuffle
算法。 - 对于
set
、map
(自身具有排序功能)的容器或者非连续性容器则无法使用。