-3

我的代码:

#include <iostream>
#include <random>

void main()
{
  std::random_device rd;

  std::cout << "Random value: " << rd() << std::endl;

  system("pause");
}

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

4

4 回答 4

4

由于您在询问如何将结果转换为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;
}
于 2013-06-09T03:11:27.747 回答
1

这是我在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.

我以前没有使用过它,但这可能会帮助您入门。

于 2013-06-09T03:10:48.293 回答
1

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

#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 ;
}

另一种转换为 a 的方法string是使用std::to_string

 str1 = std::to_string( dist(e2) ) ;
于 2013-06-09T03:16:45.583 回答
0
#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;
}
于 2013-06-09T03:09:29.293 回答