简体   繁体   中英

How to store the state of boost random number generator as const char *?

I am having difficulty figuring out how to create memory buffer of the internal state of a generator for use in c style code. I cannot store the object so I need to know the size of the generator state at compile time. I cannot use anything boost related other than this boost random header. I have to stick with stl stuff. I tried using a stringstream but it stops after it hits null characters. If I have to write a custom stream buffer it will need to be inline in the function below, I'm just not sure how to do that. My goal is to store the random number generator state in a constant size block of memory in ac structure. The easiest solution I have found is to replace boost with a c-implementation of the mersenne twister algorithm that has an easily identifiable array size.

static boost::mt19937 rngEngine;
static boost::variate_generator<boost::mt19937&, boost::uniform_int<> > generator(rngEngine, boost::uniform_int<>(0, INT_MAX));

const char * getState(void) {
    std::ostringstream content;
    content << rngEngine;
    return content.str().data();
}

Return a std::string from your getState function, and it will have the size (or length in C++03) and embedded '\\0' characters.

The code as written is undefined behavior, as the const char* outlives the string that gave it birth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM