Random shuffle and function pointers

2019-07-20 03:56发布

I have the following function, which generates an integer in a given range:

 18 int choosecard(){
 19     boost::uniform_int<> dist(0,51);
 20     boost::variate_generator< boost::mt19937&, boost::uniform_int<> > cardchoice(gen, dist);
 21     return cardchoice();
 22 }

I want to use it as an argument to std::random_shuffle, so that I can shuffle a vector of 52 integers.

 64     int (*pchoosecard)(void) = choosecard;
 65 
 66     std::random_shuffle(cards.begin(), cards.end(), pchoosecard);

However I get this error that I don't understand:

$ make
g++ -I /usr/local/boost_1_45_0/ -c main.cpp
In file included from /usr/include/c++/4.4/algorithm:62,
                 from /usr/local/boost_1_45_0/boost/any.hpp:13,
                 from /usr/local/boost_1_45_0/boost/program_options/value_semantic.hpp:12,
                 from /usr/local/boost_1_45_0/boost/program_options/options_description.hpp:13,
                 from /usr/local/boost_1_45_0/boost/program_options.hpp:15,
                 from main.cpp:1:
/usr/include/c++/4.4/bits/stl_algo.h: In function ‘void std::random_shuffle(_RAIter, _RAIter, _Generator&) [with _RAIter = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, _Generator = int (*)()]’:
main.cpp:66:   instantiated from here
/usr/include/c++/4.4/bits/stl_algo.h:4998: error: too many arguments to function
make: *** [main.o] Error 1

Everything compiles fine when I comment out the line that calls std::random_shuffle.

Is anyone able to shed some light on this problem?

2条回答
趁早两清
2楼-- · 2019-07-20 04:43

There are "too many arguments" because std::random_shuffle is trying to pass too many arguments to the callback that you gave it. So it's really too few parameters.

Your choosecard is supposed to accept one parameter, of type ptrdiff_t, which tells the function the number of elements, basically. (You are not supposed to hardcode the number of cards in this function.) So you plug that in to the boost::uniform_dist constructor.

查看更多
欢心
3楼-- · 2019-07-20 04:53

From http://www.cplusplus.com/reference/algorithm/random_shuffle/:

template <class RandomAccessIterator, class RandomNumberGenerator>
void random_shuffle ( RandomAccessIterator first, RandomAccessIterator last,
                      RandomNumberGenerator& rand );

first, last

Forward iterators to the initial and final positions of the sequence to be shuffled. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.

rand

Pointer to unary function taking one argument and returning a value, both of the appropriate difference type (generally ptrdiff_t). The function shall return a value between zero and its argument (lower than this).

查看更多
登录 后发表回答