I was reading up on this : http://www.cplusplus.com/reference/algorithm/random_shuffle/ and wondered if its possible to random_shuffle an array of int elements. This is my code
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};
cout << a << endl << endl;
random_shuffle(a[0],a[9]);
cout<<a;
}
I got this error:
error C2893: Failed to specialize function template
'iterator_traits<_Iter>::difference_type *std::_Dist_type(_Iter)'.
My question are:
Is it possible to shuffle an int array using random_shuffle
. If yes, I would like to learn how to do it.
Is random_shuffle
only applicable to templates?
What does my error mean?
You need to pass pointers to a[0]
and a[10]
, not the elements themselves:
random_shuffle(&a[0], &a[10]); // end must be 10, not 9
In C++11, you can use std::begin
and std::end
:
random_shuffle(std::begin(a), std::end(a));