1. 程式人生 > >STL random_shuffle 洗牌函數了解一下

STL random_shuffle 洗牌函數了解一下

洗牌函式的含義就是將資料打亂順序,測試程式碼如下:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <random> // std::default_random_engine
#include <time.h>
using namespace std;

#define N 5

// 自定義的generator, 用來random_shuffle.
class CSelfGenerator
{
public:
	ptrdiff_t operator() (ptrdiff_t max)
	{
		unsigned int seed = ((int)time(NULL));
		srand(seed);
		double _rand = static_cast<double>(rand());
		double temp = _rand / static_cast<double>(RAND_MAX);
		return static_cast<ptrdiff_t>(temp * max);
	}
};

int main(int argc, char** argv)
{
	// test int
	int a[9] = { 100, 200, 300, 400, 500, 600, 700, 800, 900};
	/*CSelfGenerator sg;*/
	std::random_shuffle(a, a + 9/*, sg*/);
	for (int i = 0; i < 9; i++){
		cout << a[i] << " ";
	}
	cout << endl;

	// test float
	float _float[N] = { 0.0123, 0.0234, 0.0345, 0.0456, 0.0567 };
	std::random_shuffle(_float, _float + N);
	for (int i = 0; i < N; i++){
		cout << std::fixed << _float[i] << " ";//fixed就是用一般的方式輸出浮點數,而不是科學計數法
	}
	cout << endl;

	// test double
	double _double[N] = { 1.2E-2, 2.3E-2, 3.4E-2, 4.5E-2, 5.6E-2 };
	std::random_shuffle(_double, _double + N);
	for (int i = 0; i < N; i++){
		cout << std::fixed << _double[i] << " ";
	}
	cout << endl;

	// test string
	vector<string> strArray;
	strArray.push_back("aa");
	strArray.push_back("bb");
	strArray.push_back("cc");
	strArray.push_back("dd");
	strArray.push_back("ee");
	strArray.push_back("ff");
	std::random_shuffle(strArray.begin(), strArray.end());
	for(int j = 0; j < strArray.size(); j++){
		cout << strArray[j].c_str() << " ";
	}
	cout<<endl;

	// test gen rand num
	vector<int> intArray;
	for(int i=0; i<=99; i++){
		intArray.push_back(i); 
	}
	random_shuffle(intArray.begin(), intArray.end()); // 0~99的隨機生成
	for(int i=0; i<=99; i++){
		cout << intArray[i] << " ";
	}
	cout<<endl; 

	system("pause");

	return EXIT_SUCCESS;
}

這裡面有個問題:除了最後隨機生成99個隨機數的順序被打亂了,其餘的每次執行後,順序都是一樣的!何解?

有了解的朋友,如果懂的,麻煩留個言~~