#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main (int argc, char *argv[])
{
int n = 10;
vector<int> v;
//append integers 0 to n-1 to v
for (int i = 0; i < n; ++i) {
v.push_back(i);
}
//random shuffle the values of v
random_shuffle (v.begin(), v.end());
//print all values of v to screen
copy (v.begin(), v.end(), ostream_iterator<int> (cout, "\n"));
return 0;
}
运行结果:1.其函数原型如下:
template <class RandomAccessIterator>
void random_shuffle ( RandomAccessIterator first, RandomAccessIterator last );
template <class RandomAccessIterator, class RandomNumberGenerator>
void random_shuffle ( RandomAccessIterator first, RandomAccessIterator last,
RandomNumberGenerator& rand );
Rearranges the elements in the range [first,last) randomly.
The function swaps the value of each element with that of some other randomly chosen element. When provided, the function rand chooses which element.
The behavior of this function template is equivalent to:
template <class RandomAccessIterator, class RandomNumberGenerator>
void random_shuffle ( RandomAccessIterator first, RandomAccessIterator last,
RandomNumberGenerator& rand )
{
iterator_traits<RandomAccessIterator>::difference_type i, n;
n = (last-first);
for (i=n-1; i>0; --i) swap (first[i],first[rand(i+1)]);
}
// random_shuffle example
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
// random generator function:
ptrdiff_t myrandom (ptrdiff_t i) { return rand()%i;}
// pointer object to it:
ptrdiff_t (*p_myrandom)(ptrdiff_t) = myrandom;
int main () {
srand ( unsigned ( time (NULL) ) );
vector<int> myvector;
vector<int>::iterator it;
// 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() );
// using myrandom:
random_shuffle ( myvector.begin(), myvector.end(), p_myrandom);
// print out content:
cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}