文本数据挖掘---课后作业shuffle函数洗牌C++


题目:

代码如下:
#include <iostream> #include <random> #include <algorithm> #include <vector> #include <sstream> int main() { int N, num0, num1, l; std::vector<int>v2;//输入的任意vector,用空格隔开; std::string line; std::getline(std::cin, line); std::istringstream iss(line); for (int d; iss >> d; v2.push_back(d)) {} l = v2.size();//用iss获取vector长度l; std::cin >> N;//输入采样数量N; std::vector<int> v1(5000000, 0); v1.insert(v1.end(), 5000000, 1);//构造容器V1存放500w个1和0; std::vector<int>v; v.insert(v.end(), v1.begin(), v1.end()); v.insert(v.end(), v2.begin(), v2.end());//insert叠加两个vector; std::random_device rd; std::mt19937 rng(rd());//设置随机数种子; std::shuffle(v.begin(), v.end(), rng);//shuffle函数洗牌; v.resize(N);//设置要输出的容器大小; /*std::cout << "after shuffle: \t"; for (int n : v) { std::cout << n << " "; }*///可以用来查看洗牌后的数组; std::cout << std::endl; num0 = count(v.begin(), v.end(), 0);//计数器统计个数; num1 = count(v.begin(), v.end(), 1); std::cout << "数字0出现的个数: \t"; std::cout << num0; std::cout << std::endl; std::cout << "数字1出现的个数: \t"; std::cout << num1; return 0; }

运行结果:

 

 

 

 

 

posted @ 2022-09-24 12:19  slowlydance2me  阅读(30)  评论(0编辑  收藏  举报