赞
踩
- #include <iostream>
- #include <chrono>
- #include <random>
-
- int main()
- {
- // obtain a seed from the system clock:
- unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
-
- std::mt19937 generator(seed); // mt19937 is a standard mersenne_twister_engine
- auto number = generator();//生成一个随机数
- std::cout << "Random value: " << number << std::endl;
-
- return 0;
- }
输出:
Random value: 3878294182
下面的代码来自官方示例:
- // mersenne_twister_engine constructor
- #include <iostream>
- #include <chrono>
- #include <random>
- #include <string>
-
- using namespace std;
-
- int main()
- {
- // obtain a seed from the system clock:
- unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
-
- // obtain a seed from the user:
- std::string str;
- std::cout << "Please, enter a seed: ";
- std::getline(std::cin, str);
- std::seed_seq seed2(str.begin(), str.end());
-
- std::mt19937 g1(seed1); // mt19937 is a standard mersenne_twister_engine
- std::cout << "A time seed produced: " << g1() << std::endl;
- std::cout << typeid(g1()).name() << endl;
- std::mt19937 g2(seed2);
- std::cout << "Your seed produced: " << g2() << std::endl;
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。