我如何获得随机值在c++ 11

How do i get random value in c++ 11

本文关键字:c++ 随机 何获得      更新时间:2023-10-16

我的代码:

#include <iostream>
#include <random>
void main()
{
  std::random_device rd;
  std::cout << "Random value: " << rd() << std::endl;
  system("pause");
}

如何获得结果rd(),并将其转换为std::string ?

既然您正在询问如何将std::random_device的结果转换为字符串,而std::random_device返回unsigned int c++ 11提供std::to_string,可用于将数字转换为字符串。看到这里。

#include <iostream>
#include <random>
#include <string>
int main()
{
    std::random_device rd;
    std::string str = std::to_string(rd());
    std::cout << str << std::endl;
    return 0;
}

下面是我在http://en.academic.ru/dic.nsf/enwiki/11574016上找到的一个例子

#include <random>
#include <functional>
std::uniform_int_distribution<int> distribution(0, 99);
std::mt19937 engine; // Mersenne twister MT19937
auto generator = std::bind(distribution, engine);
int random = generator();  // Generate a uniform integral variate between 0 and 99.
int random2 = distribution(engine); // Generate another sample directly using the       distribution and the engine objects.

我以前没有使用过它,但这可能会帮助你开始。

std::stringstream是将数字转换为字符串的一种方法,下面的代码显示了各种可能的引擎和分布。对于引擎和normal distribution,默认为Mersenne Twister。对于可用的选项,这是一个很好的参考:

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <sstream>
int main()
{
    std::random_device rd;
    //
    // Engines 
    //
    std::mt19937 e2(rd());
    //std::knuth_b e2(rd());
    //std::default_random_engine e2(rd()) ;
    //
    // Distribtuions
    //
    std::normal_distribution<> dist(2, 2);
    //std::student_t_distribution<> dist(5);
    //std::poisson_distribution<> dist(2);
    //std::extreme_value_distribution<> dist(0,2);
    std::stringstream s1 ;
    s1 << dist(e2) ; 
    std::string str1 = s1.str();
    std::cout << str1 << std::endl ;
}
另一种转换为string的方法是使用std::to_string:
 str1 = std::to_string( dist(e2) ) ;
#include <stdlib.h>
#include <time.h>
int main(){
    srand(time(NULL));
    unsigned int maxValue = 50;
    std::cout << "Random value: " << rand()%maxValue; //random between 0-50
    return 0;
}