C++ 在全为1的数组中随机三个位置为0

std:random_device 是一个在 C++ 标准库中用于生成非确定性随机数的类,头文件<random>。它通常用于为随机数生成器(如std:mt19937 )提供种子,以确保每次程序运行时都能产生不同的随机数序列。 


std:iota 是 C++ 标准库中的一个函数,定义在<numeric>头文件中。它用于给容器中的元素赋值,从指定的开始值开始,并逐个递增。


std.shufle 函数的作用是对给定范围内的元素进行随机重排。(使用 std:shufle 函数打乱容器中元素的顺序后,原始顺序是无法直接复原的,因为 std:shufle 不记录任何关于元素原始顺序的信息。如果需要在打乱后能够恢复到原始顺序,可以使用一个额外的容器来存储原始顺序。)

#include<iostream>
#include<numeric>
#include<vector>
#include<random>
using namespace std;
int main() {
	//在全为1的数组中随机三个位置为0
	vector<int> array(64, 1);
	random_device rd; 
    mt19937 gen(rd());

	vector<int> indices(64);

	cout << "array数组:" << endl;
	for (int i = 0; i < 64; ++i) {
		cout << array[i] << ' ';
		if (!((i + 1) % 8)) cout << endl;
	}cout << endl;

	iota(indices.begin(), indices.end(), 0);//从0开始递增,0、1、2...63

	cout << "indices数组:" << endl;
	for (int i = 0; i < 64; ++i) {
		cout << indices[i] << ' ';
		if (!((i + 1) % 8)) cout << endl;
	}cout << endl;

	
	shuffle(indices.begin(), indices.end(), gen);//gen作为随机数生成器

	cout << "indices数组:" << endl;
	for (int i = 0; i < 64; ++i) {
		cout << indices[i] << ' ';
		if (!((i + 1) % 8)) cout << endl;
	}cout << endl;

	//取出indices的前三个随机位置的数作为array的随机位置设置为0
	for (int i = 0; i < 3; ++i) {
		array[indices[i]] = 0;
	}

	cout << "array数组:" << endl;
	for (int i = 0; i < 64;++i) {
		cout << array[i] << ' ';
		if (!((i+1) % 8)) cout << endl;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值