CPP-STL:随机数发生器random_shuffle
//--------------------------------------------------------------------------- #include <string.h> #include <vector> #include <algorithm> #include <iostream.h> #include <ctime> // std::time #pragma hdrstop //--------------------------------------------------------------------------- #pragma argsused
int main(int argc, char* argv[]) { vector<string> vs; vs.push_back(string ("aa")); vs.push_back (string ("bb")); vs.push_back (string ("cc")); vs.push_back (string ("dd")); vs.push_back (string ("ee")); std::srand(unsigned(time(0))); //srand函数是随机数发生器的初始化函数 random_shuffle(vs.begin(), vs.end()); /* 打乱顺序 */ for (int i = 0; i< 5; i++) cout<<vs[i]<<"\n"; /* 显示打乱顺序后的元素 */ system("pause"); return 0; }
以上代码里的random_shuffle使用随机种子,不写第三个参数。
下面一个例子,使用自定义的随机种子myrandom
// random generator function: int myrandom (int i) { return std::rand()%i; } std::vector<int> myvector; // set some values: for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
std::srand ( unsigned ( std::time(0) ) );//srand函数是随机数发生器的初始化函数。
// using built-in random generator:
//std::random_shuffle ( myvector.begin(), myvector.end() );
// using myrandom:
std::random_shuffle ( myvector.begin(), myvector.end(), myrandom);
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << '' << *it;
std::cout << '\n';
system("pause"); return 0; }