2010-12-04 81 views
2

我有以下的功能,即在給定的範圍內產生一個整數隨機洗牌和函數指針

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個整數。

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行。

有人能夠解釋這個問題嗎?

回答

1

有太多的論據,因爲std::random_shuffle正試圖通過太多的參數傳遞給你的回調。所以它真的太參數。

您的choosecard應該接受一個參數,類型ptrdiff_t,它基本上告訴函數元素的數量。 (您不應該在此函數中硬編碼卡的數量。)因此,您將其插入到構造函數boost::uniform_dist中。

+0

謝謝,但我還是很困惑。我沒有uniform_dist構造函數。你的意思是boost :: uniform_int <> dist(0,51)的行嗎?我已經選擇了一個ptrdiff_t,我。然後將上述行更改爲boost :: uniform_int <> dist(0,i-1); 但是我只是越來越神祕的錯誤 – oadams 2010-12-04 08:04:07

1

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

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

第一,最後

正向迭代到該序列的至 的初始和最終位置 進行改組。使用的範圍是 [first,last),其中包含第一個和最後一個之間的所有 元素, 包括第一個 指向的元素,但不包含last指向的元素。

蘭特

指向一元函數帶一個參數並返回一個值, 兩者適當差 類型(通常ptrdiff_t型)的。 函數將返回一個介於 零之間的值和它的參數(低於 this)。