我有以下函数,它生成给定范围内的整数:
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 }
我想将它用作 std::random_shuffle 的参数,这样我就可以随机播放一个包含 52 个整数的 vector 。
64 int (*pchoosecard)(void) = choosecard;
65
66 std::random_shuffle(cards.begin(), cards.end(), pchoosecard);
但是我得到了这个我不明白的错误:
$ 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
当我注释掉调用 std::random_shuffle 的行时,一切都可以正常编译。
有人能阐明这个问题吗?
最佳答案
“参数太多”是因为 std::random_shuffle
试图将太多参数传递给您提供的回调。所以它确实很少参数。
您的 choosecard
应该接受一个类型为 ptrdiff_t
的参数,它基本上告诉函数元素的数量。 (你不应该在这个函数中硬编码卡片的数量。)所以你将它插入 boost::uniform_dist
构造函数。
关于c++ - 随机洗牌和函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4352346/