参考网址:
https://44.wendadaohang.com/c/975299840891834337.html
https://blog.csdn.net/weixin_43919932/article/details/111317902
https://www.delftstack.com/zh/howto/cpp/how-to-convert-vector-to-array-in-cpp/
思路就是先生成自己想要数量的1以及0,然后再将这组数据进行打乱就好了。
- 由于第一个网址中的程序中会出现error:"未定义标识符 “random_shuffle”,查了很多,发现应该是最新版的c++已经将它替换了,应该将其改为std::shuffle。
- 但是我换成上面那个之后又显示错误:“没有与参数列表匹配的 函数模板 “std::__1::shuffle” 实例”,于是又各种查找,终于找到了下面的代码(参考的第二个网址)。
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <random>
using namespace std;
vector<int>RandChip(int n,int m)//随机模拟nchip,mGood
{
int count=0;
srand(time(0));//随机种于
vector <int> a;
std::random_device rd;
std::mt19937 g(rd()); // 随机数引擎:基于梅森缠绕器算法的随机数生成器
for (int i=0;i<m;i++)
a.push_back (1);
for (int i=m;i<n;i++)
a.push_back (0);
std::shuffle(a.begin(), a.end(),g);//打乱元素
return a;
}
int main()
{
int e[10];
vector<int> b=RandChip(10,3);
copy(b.begin(), b.end(), e);
for (int i = 0; i < 10; i++) {
cout << e[i] << " ";
}
cout<<endl;
}
对代码解释一下
- 最终生成的结果是随机生成10个数的0、1变量,其中1的个数为3个。
- 其中copy(b.begin(), b.end(), e);为将向量中的数据保存到数组中,具体参考第三个链接。
纯粹是自己编程过程中遇到的困难及解决办法,记录一下以免忘记。具体内容有很多不好的地方,如果有人看到,请见谅。