Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to random_shuffle an array of int elements?

Tags:

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:

  1. Is it possible to shuffle an int array using random_shuffle. If yes, I would like to learn how to do it.

  2. Is random_shuffle only applicable to templates?

  3. What does my error mean?

like image 730
Computernerd Avatar asked Feb 06 '13 01:02

Computernerd


People also ask

How do you randomly shuffle an array?

shuffle(Arrays. asList(array)); then making a shuffle your self. @Louie Collections. shuffle(Arrays.

How do you scramble an array in C++?

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.


2 Answers

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)); 
like image 148
Sergey Kalinichenko Avatar answered Oct 02 '22 15:10

Sergey Kalinichenko


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.

like image 31
Mankarse Avatar answered Oct 02 '22 17:10

Mankarse