Randomly Shuffling Data - C++ STL Algorithm

C++ examples for STL Algorithm:random_shuffle

Description

Randomly Shuffling Data

Demo Code

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;
template<typename C>
void printContainer(const C& c, char delim = ',', ostream& out = cout) {
   printRange(c.begin(), c.end(), delim, out);
}

template<typename Fwd>
void printRange(Fwd first, Fwd last, char delim = ',', ostream& out = cout) {
   out << "{";
   while (first != last) {
      out << *first;//  ww w  .  j a  v a  2 s .c o  m
      if (++first != last)
         out << delim << ' ';
   }
   out << "}" << endl;
}

int main() {

   vector<int> v;
   back_insert_iterator<std::vector<int> > p = back_inserter(v);

   for (int i = 0; i < 10; ++i)
     *p = i;

   printContainer(v, true);

   random_shuffle(v.begin(), v.end());

   printContainer(v, true);
}

Result


Related Tutorials