我的代码:
#include <iostream>
#include <random>
void main()
{
std::random_device rd;
std::cout << "Random value: " << rd() << std::endl;
system("pause");
}
如何获得结果rd()
,并将其转换为std::string
?
答案 0 :(得分:4)
由于您询问如何将std::random_device
的结果转换为字符串,std::random_device
会返回unsigned int
。 C ++ 11 提供std::to_string
,可用于将数字转换为字符串。请参阅here。
#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;
}
答案 1 :(得分: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.
我之前没有使用它,但这可能会帮助你开始。
答案 2 :(得分:1)
std::stringstream
是将数字转换为字符串的一种方法,下面的代码显示了各种引擎和分布。对于引擎和Mersenne Twister
,默认为normal distribution
。对于可用选项,这是很好的reference:
#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) ) ;
答案 3 :(得分: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;
}