std::mt19937 e; // Mersenne Twister engine
std::uniform_int_distribution<int> u(0,99999); // uniform ints 0 to 99999, inclusive
auto rng = std::bind(u,e); // so rng() retuns the next random number
And filling a vector with random numbers could look like this: std::vector<int> nums(1000);
std::generate(nums.begin(), nums.end(), rng);
This last line can be written in C++20 more simply like this: std::ranges::generate(nums,rng); for (int i = 0; i < nums.size(); i++) {
nums[i] = rng();
}
Simple, easy to understand, actually compiles to efficient code even in Debug mode, don't need to include <algorithm> header which includes 10000+ lines of STL code which bloats compile times, etc. for (int i : nums) {
nums[i] = rng();
}
Edit: Ooops, I'm an idiot, this doesn't do anything useful (i is every value in nums, not the indices of nums...)Like, wouldn't it be
for (int num : nums) {
num = rng();
}
(I don't know any c++). I kind of expect the above not to work though because it's doing an assignment. I suppose this is a good argument to just use a `fill` or `generate` function... for (int i = 0; i < nums.size(); ++i) {
nums[nums[i]] = rng();
}
Which happens not to go out of bounds simply because nums[i] is initially 0 for every i in the range - so it sets nums[0] to a different random number 1000 times.* The C++ Programming Language, 4th edition by Bjarne Stroustrup - The biggest change in the language was the introduction of C++11 and this book covers it well.
* A Tour of C++, 3rd edition by Bjarne Stroustrup - Summary of all changes upto C++20.
* Software Architecture with C++: Design modern systems using effective architecture concepts, design patterns, and techniques with C++20 by Adrian Ostrowski et.al. - More like a broad survey rather than in-depth but covers development in a "modern ecosystem".
* Modern C++ Programming Cookbook: Master C++ core language and standard library features, with over 100 recipes, updated to C++20, 2nd Edition by Marius Bancila - A series of articles one each for a language feature.
Usage examples have often been updated to current best practice.