Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

c++ - Is it possible to random_shuffle an array of int elements?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...