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?
shuffle(Arrays. asList(array)); then making a shuffle your self. @Louie Collections. shuffle(Arrays.
Shuffle an Array using STL in C++ These are namely shuffle() and random_shuffle(). This method rearranges the elements in the range [first, last) randomly, using g as a uniform random number generator. It swaps the value of each element with that of some other randomly picked element.
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));
random_shuffle takes iterators, rather than elements. Try either:
std::random_shuffle(a, a + 10); or
std::random_shuffle(std::begin(a), std::end(a)); std::random_shuffle can be used on any pair of random access iterators, and will shuffle the elements in the range denoted by those iterators.
The error occurs because ints are not iterators, and so std::random_shuffle is unable to use the given ints as iterators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With