英文:
Get different random bytes each run
问题
我想在C++中生成一堆随机字节。为此,我使用以下代码:
```c++
#include <climits>
#include <functional>
#include <random>
#include <vector>
#include <iostream>
using random_bytes_engine = std::independent_bits_engine<
std::default_random_engine, CHAR_BIT, unsigned char>;
int main()
{
random_bytes_engine rbe;
std::vector<unsigned char> data(10);
std::generate(begin(data), end(data), std::ref(rbe));
for(int b: data) {
std::cout << b << ", ";
}
std::cout << std::endl;
}
166, 240, 216, 41, 129, 199, 215, 253, 66, 76,
不错。现在,我想确保每次运行程序时都获得不同的值,也就是说,我想从某个地方对independent_bits_engine
进行种子化。
有任何提示吗?解决方案必须跨平台。(除了independent_bits_engine
之外的可移植解决方案也可以使用。)
<details>
<summary>英文:</summary>
I'd like to generate a bunch of random bytes in C++. For this, I use
```c++
#include <climits>
#include <functional>
#include <random>
#include <vector>
#include <iostream>
using random_bytes_engine = std::independent_bits_engine<
std::default_random_engine, CHAR_BIT, unsigned char>;
int main()
{
random_bytes_engine rbe;
std::vector<unsigned char> data(10);
std::generate(begin(data), end(data), std::ref(rbe));
for(int b: data) {
std::cout << b << ", ";
}
std::cout << std::endl;
}
166, 240, 216, 41, 129, 199, 215, 253, 66, 76,
Nice. Now, I'd like to make sure that I get different values each time I run the program, i.e., I'd like to seed the independent_bits_engine
from somewhere.
Any hints? The solution must be cross-platform. (Portable solutions other than independent_bits_engine
would also work.)
答案1
得分: 1
文档中有一个示例,但它略微隐藏,因为它是为构造函数而提到的,而不是为主类:
std::random_device rd;
std::independent_bits_engine<std::mt19937, /*bits*/ 3, unsigned long> e3(rd()); // 由rd()种子化
这里的random_device
实例代表特定于系统的随机数生成器,如此处所指定。当然,您仍然需要验证是否存在这样的随机数生成器,但我想这是在不使用特定于系统的功能的情况下获得的最随机的情况。有关生成的随机性的安全性的讨论可以在这里找到。
英文:
There is an example in the documentation, but it is slightly hidden as it is mentioned for the constructor, not for the main class:
std::random_device rd;
std::independent_bits_engine<std::mt19937, /*bits*/ 3, unsigned long> e3(rd()); // seeded with rd()
Where the instance of random_device
represents the system specific random number generator, as specified here. Of course, you'd still have to verify that there is such a random number generator present, but I guess this is about as random as it gets without using system specific functionality. A discussion on the security of the randomness generated can be found here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论