c++ 生成容器元素生成随机数
// random_shuffle example #include <iostream> // cout #include <algorithm> // random_shuffle #include <vector> // vector #include <ctime> // time #include <cstdlib> // rand, srand using namespace std; // random generator function: int myrandom (int i) { return rand()%i;} int main () { srand ( unsigned ( time(0) ) ); 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 // using built-in random generator: random_shuffle ( myvector.begin(), myvector.end() ); // print out content: cout << "using built-in random generator , myvector contains:"; for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) cout << ' ' << *it; cout << '\n'; // using myrandom: random_shuffle ( myvector.begin(), myvector.end(), myrandom); // print out content: cout << " using myrandom , myvector contains:"; for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) cout << ' ' << *it; cout << '\n'; return 0; }
输出
using built-in random generator , myvector contains: 1 4 8 5 9 7 2 3 6 using myrandom , myvector contains: 3 7 8 9 4 2 5 1 6