开发者

Hiding RNG inside class

开发者 https://www.devze.com 2023-01-28 17:51 出处:网络
I am currently implementing a Deck class that represents a 52 card playing deck. It uses the boost Random library to shuffle integers that represent cards.

I am currently implementing a Deck class that represents a 52 card playing deck. It uses the boost Random library to shuffle integers that represent cards.

#include <iostream>
#include <fstream>
#include "constants.hpp"
#include <boost/program_options.hpp>

#include <vector>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>

boost::mt19937 gen(std::time(0));

class Deck{
    private:
        std::vector<int> cards;
        int cardpointer;
        static ptrdiff_t choosecard(ptrdiff_t i);
        ptrdiff_t (*pchoosecard)(ptrdiff_t);开发者_JS百科
    public:
        Deck();
        void shuffle();
        int pop();
};

Deck::Deck(){
    for(int i=1; i<=52; i++){
        cards.push_back(i);
    }
    cardpointer = -1;
    pchoosecard = &choosecard;
}

ptrdiff_t Deck::choosecard(ptrdiff_t i){
    boost::uniform_int<> dist(0,i);
    boost::variate_generator< boost::mt19937&, boost::uniform_int<> > cardchoice(gen, dist);
    return cardchoice();
}

void Deck::shuffle(){
    std::random_shuffle(cards.begin(), cards.end(), pchoosecard);
}

I want to move the "boost::mt19937 gen(std::time(0));" line to be part of the class, however I'm having problems doing so, since I get this error when I move it into the class definition:

$ make
g++ -I /usr/local/boost_1_45_0/ -c main.cpp
main.cpp:22: error: ‘std::time’ is not a type
main.cpp:22: error: expected ‘)’ before numeric constant
main.cpp:22: error: expected ‘)’ before numeric constant
main.cpp:22: error: expected ‘;’ before numeric constant
main.cpp: In static member function ‘static ptrdiff_t Deck::choosecard(ptrdiff_t)’:
main.cpp:39: error: ‘gen’ was not declared in this scope
make: *** [main.o] Error 1


If you're making it a normal class variable, initialize it in the constructor:

class Deck {
    ...
    public:
        boost::mt19937 gen;
};

Deck::Deck() : gen(std::time(0))
{
    ...
}

If you're making it static (it looks like you are, since you're using gen from choosecard, which is static), you still need a declaration outside the class:

class Deck {
    ...
    public:
        static boost::mt19937 gen;
};

boost::mt19937 Deck::gen(std::time(0));


This is a guess based on what I think you did. You'll have to separate the definition from the initialisation of the static gen member:

class Deck {
    static boost::mt19937 gen;
    // ...
};

boost::mt19937 Deck::gen(std::time(0));


class Deck{
    boost::mt19937 gen;
    ...
};

Deck::Deck(): gen(std::time(0)){
...
}

Deck::Deck(uint32_t seed): gen(seed){
...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消