25

我正在阅读此内容:http : //www.cplusplus.com/reference/algorithm/random_shuffle/ 并想知道它是否可以 random_shuffle 一个 int 元素数组。这是我的代码

#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;
}

我收到了这个错误:

error C2893: Failed to specialize function template
    'iterator_traits<_Iter>::difference_type *std::_Dist_type(_Iter)'.

我的问题是:

  1. 是否可以使用random_shuffle. 如果是,我想学习如何做到这一点。

  2. random_shuffle仅适用于模板吗?

  3. 我的错误是什么意思?

4

5 回答 5

54

您需要传递指向a[0]anda[10]的指针,而不是元素本身:

random_shuffle(&a[0], &a[10]); // end must be 10, not 9

在 C++11 中,您可以使用std::beginand std::end

random_shuffle(std::begin(a), std::end(a));
于 2013-02-06T01:35:42.053 回答
3

尝试更换

random_shuffle(a[0],a[9]);

random_shuffle(&a[0], &a[10]);

来自:http ://www.java2s.com/Code/Cpp/STL-Basics/Userandomshufflealgorithmswitharray.htm

于 2013-02-06T01:41:35.677 回答
3

random_shuffle接受迭代器,而不是元素。尝试:

std::random_shuffle(a, a + 10);

或者

std::random_shuffle(std::begin(a), std::end(a));

std::random_shuffle可以在任何一对随机访问迭代器上使用,并且会在这些迭代器表示的范围内打乱元素。

发生错误是因为ints 不是迭代器,因此std::random_shuffle无法将给定int的 s 用作迭代器。

于 2013-02-06T07:01:14.240 回答
1

Just changing the arr to a pointer does not solve the solution. This will make the array swap to one type of permutation. This means that if you rerun the program, your array will be shuffled into the exact same way as it did in the previous run.

To fix this - the function offers a third parameter which acts as a seed. So the correct implementation of the function is as follows.

1) Have a function or a lamda that generates a random number. This will act as your seed.

int myrandom (int i) { return std::rand()%i;}

Make sure to set the seed of the internal random number generator.

std::srand ( unsigned ( std::time(0) ) );

2) Insert this function as the third arguement in the random_shuffle function call.

std::random_shuffle ( myvector.begin(), myvector.end(), myrandom);

This will result in an always random shuffled array. Make sure to include the following:

#include <algorithm>    // std::random_shuffle
#include <vector>       // std::vector
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand
于 2017-07-21T09:29:17.423 回答
0

以这种方式为我工作:

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int a[10]={0,1,2,3,4,5,6,7,8,9};

    for (unsigned i = 0; i < 10; i++)
    {
        cout << a[i];
    }
    cout << endl;

    random_shuffle(&a[0],&a[10]);

    for (unsigned i = 0; i < 10; i++)
    {
        cout << a[i];
    }
    cout << endl;
}
于 2014-10-17T19:24:16.120 回答