The following is actually a stream (std :: istream) and uses the C ++ 11 <random> library.
It is not particularly written to be quick, but it is fun:
#include <iostream> #include <string> #include <array> #include <algorithm> #include <random> class RandomBuf : public std::streambuf { private: size_t m_size; std::array<char, 64> m_buf; std::mt19937_64 m_twister; std::uniform_int_distribution<char> m_dist; protected: int_type underflow() override { if (m_size == 0) return EOF; size_t size = std::min(m_size, m_buf.size()); setg(&m_buf[0], &m_buf[0], &m_buf[size]); for (size_t i = 0; i < size; ++i) m_buf[i] = m_dist(m_twister); m_size -= size; return 0; } public: RandomBuf(size_t size, char b, char e) : m_size(size), m_dist(b, e) { } }; class Random : public std::istream { private: RandomBuf m_streambuf; public: Random(size_t size, char b, char e) : m_streambuf(size, b, e) { rdbuf(&m_streambuf); } }; // Example usage: int main() { Random random(100, 'a', 'z'); // Create an istream that produces 100 pseudo-random characters in the interval ['a', 'z']. // Read random stream to a string: std::string str; random >> str; // Print result. std::cout << str << std::endl; }
The output of this program (precisely because the standard guarantees that the default Mersenne twister has a given initial number):
ugsyakganihodonwmktggixegfszuclgupylingbnscxadzqhjmhhyqtssbmctlpchqfflzfwhvjywmajtnkaxczrmtpnlvwmzxd
EDIT:
For extra bonus points, I added the StreamHasher class: https://wandbox.org/permlink/bIDCVTnJjkdafARo
Just added classes:
class StreamHasherBuf : public std::streambuf { private: size_t m_hash; std::array<char, 64> m_buf;
for instance
int main() { RandomBuf random(100, 'a', 'z');
source share