c++ 从指定数据中随机抽取数据

#include <iostream>

#include <ctime>
#include <vector>


std::vector<int> vpool{ 20,30,60,40 };


void getOne(std::vector<int>& v1)
{
	std::srand((unsigned)time(NULL));
	int len =(int) vpool.size();

	int tmpvalue = -1;
	do 
	{
	   tmpvalue = rand() % len;

		if (v1.empty())
		{
			v1.push_back(vpool[ tmpvalue] );
			return;
		}
		std::vector<int>::iterator	itr = std::find(v1.begin(), v1.end(), vpool[tmpvalue]);

		if (itr == v1.end())
		{
			v1.push_back(vpool[tmpvalue]);
			return;
		}
		tmpvalue = -1;

	} while (tmpvalue==-1);

}


void lottery(std::vector<int>& v1, int num)
{
	int n = (num < vpool.size()) ? num : vpool.size();

	for (int i = 0;i < n;++i)
	{
		 getOne(v1);
	}
}


int main()
{

	std::vector<int> getpool;

	lottery(getpool,2);
	
	for (auto itr = getpool.begin();itr != getpool.end();++itr)
	{
	   std::cout << *itr << std::endl;
	}

}

猜你喜欢

转载自blog.csdn.net/m0_37981386/article/details/108332955
今日推荐