【C++STL】随机排序(random_shuffle)的使用

3 篇文章 1 订阅

一、STL算法概述

  1. 算法主要包含在头文件<algorithm> <functional> <numeric>中。
  2. <algorithm>是所有STL头文件中最大的,涉及到:遍历、比较、 查找、交换、复制、修改等操作。
  3. <functional>定义了一些模板类,用来声明函数对象。
  4. <numeric>最小,只包含几个在序列上进行简单数学运算的模板函数。

二、random_shuffle

功能:洗牌,随机调整指定范围内元素的次序

  • random_shuffle()算法包含在头文件<algorithm>
函数原型:random_shuffle(iterator beg, iterator end)解释
参数1iterator beg开始迭代器
参数2iterator 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算法。
  • 对于setmap(自身具有排序功能)的容器或者非连续性容器则无法使用。

如果这篇文章对你有所帮助,渴望获得你的一个点赞!

在这里插入图片描述

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

OpenC++

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值