I'm trying to display a random number in the array of 5 ints. I have an int distribution from 0 to the size of the array. But whenever I go to output the numbers, sometimes I get a garbage value. Why is this happening?
#include <iostream>
#include <random>
int main()
{
int a[5] = { 1, 2, 3, 4, 5 };
std::random_device seed;
std::default_random_engine rand(seed());
std::uniform_int_distribution<int> dist(0, sizeof(a)/sizeof(*a));
for (int i = 0; i < 100; ++i)
std::cout << a[dist(rand)] << "\n";
}
Array indexes are zero-based . For an array of 5 elements the valid indexes are 0..4
. Your distribution returns values in the range 0..5
and is the source of the problem.
Because of undefined behavior - your are accessing an element outside the bounds of array a
. Since the distribution goes from 0
to X
and not 0
to one before X
you should construct it like so.
std::uniform_int_distribution<int> dist(0, sizeof(a)/sizeof(*a) - 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.