Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
367 views
Welcome To Ask or Share your Answers For Others

1 Answer

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...