To generate random numbers in C++, you use the <random> header, which provides modern, flexible, and statistically sound generators. The basic pattern is: create a random engine (like std::mt19937), seed it with a random device, then use a distribution (like std::uniform_int_distribution) to get numbers in your desired range. This replaces the old C-style rand() and srand(), which are less reliable and harder to control.
What You’ll Need
- A C++ compiler that supports C++11 or later (most modern compilers do, e.g., GCC, Clang, MSVC).
- A text editor or IDE (Visual Studio, Code::Blocks, CLion, or just a plain editor with command-line compilation).
- Basic familiarity with compiling and running a C++ program.
Step-by-Step
- Include the necessary headers. Add
#include <iostream>for output and#include <random>for random number generation. - Create a random device. This is a source of true randomness (like hardware entropy). Declare:
std::random_device rd;. This will be used to seed the engine. - Create a random engine. The most common is
std::mt19937(Mersenne Twister). Seed it with the random device:std::mt19937 gen(rd());. This engine generates raw random bits. - Define a distribution. This converts the engine’s output into numbers you want. For integers, use
std::uniform_int_distribution<int> dist(1, 100);to get numbers between 1 and 100 inclusive. For doubles, usestd::uniform_real_distribution<double> dist(0.0, 1.0);. - Generate a random number. Call the distribution with the engine as an argument:
int random_number = dist(gen);. Each call gives a new random value. - Put it all together. Here’s a complete example that prints 10 random integers between 1 and 100:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dist(1, 100);
for (int i = 0; i < 10; ++i) {
std::cout << dist(gen) << " ";
}
std::cout << std::endl;
return 0;
}
Compile and run. You should see 10 different numbers each time you run the program.
Common Mistakes
- Using
rand()without seeding. If you callrand()withoutsrand(), you get the same sequence every run. Even with seeding, the quality is poor. - Seeding with a constant. Using
std::mt19937 gen(42);always gives the same sequence. That’s fine for debugging, but not for real randomness. - Creating a new engine inside a loop. If you create the engine and distribution inside the loop, you re-seed each time, which can produce repeated numbers or slow down the program. Create them once outside the loop.
- Using modulo to get a range.
rand() % 100introduces bias because the range may not divide evenly into the generator’s max. The distribution classes handle this correctly. - Forgetting to include
<random>. You’ll get compile errors about undefined types.
Tips
- Use
std::mt19937for most tasks. It’s fast and has good quality. For cryptographic security, usestd::random_devicedirectly, but note it can be slow or block. - Reuse the engine and distribution. Creating them once and reusing them is efficient and maintains good statistical properties.
- For reproducible results. Seed with a fixed value (e.g.,
std::mt19937 gen(12345);) when you need to debug or replay a simulation. - For floats, use
std::uniform_real_distribution. It gives a uniform distribution in [a, b). To include b, usestd::nextafter(b, std::numeric_limits<double>::max())as the upper bound. - Use
std::shufflefor containers. If you need to randomize a vector, usestd::shuffle(vec.begin(), vec.end(), gen);instead of manually picking indices.
Troubleshooting
- Compilation error: ‘random_device’ is not a member of ‘std’. Your compiler might not support C++11. Add
-std=c++11(or later) to your compile command. For GCC/Clang:g++ -std=c++11 program.cpp. - Program always gives the same numbers. Check that you’re seeding with
rd()and not a constant. Also, ensure you’re not creating the engine inside a loop. - Random numbers are not uniform. This usually happens when you use
rand() % range. Switch to the distribution classes. - Getting negative numbers unexpectedly. If you use
std::uniform_int_distributionwith a negative range, that’s fine, but make sure your type is signed. For unsigned types, useunsignedin the template. - Program crashes when using
std::random_device. On some platforms,random_devicemay not be available (e.g., MinGW on Windows). A workaround is to use a seed fromtime(0)orchronoas a fallback, but note that’s less secure.
Frequently Asked Questions
- What’s the difference between
rand()and<random>?rand()is a simple C function with limited range and quality.<random>provides multiple engines and distributions, giving better randomness and control. - Can I generate a random double between 0 and 1? Yes, use
std::uniform_real_distribution<double> dist(0.0, 1.0);. Note that the upper bound is exclusive, so you get numbers in [0, 1). - How do I generate a random boolean? Use
std::uniform_int_distribution<int> dist(0, 1);and treat 0 as false, 1 as true. Or usestd::bernoulli_distribution. - Is
std::random_devicesecure for passwords? It can be, but it’s not guaranteed. For cryptographic purposes, use a dedicated library like OpenSSL.std::random_deviceis not standardized to be cryptographically secure. - Why do I get the same sequence when I use
std::mt19937without seeding? The default seed is fixed, so you get the same sequence every time. Always seed withrd()for non-deterministic behavior. - Can I use
std::random_devicedirectly to generate numbers? Yes, you can, but it’s not recommended because it may be slow and can block waiting for entropy. Use it only to seed an engine.
Related
- Cell Counting Techniques: Hemocytometer, Automated, and More
- How to Split a String in C++ (with Code Examples)
- Split Values in SQL: How to Separate Delimited Text
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Protect Sheet Without a Password: What WorksYes. In Excel for Microsoft 365 on Windows, choose Review > Protect Sheet, set the permissions you want,…
- Excel Merge Cells: Combine Content Without Losing DataNo: Excel’s Merge & Center command does not combine the contents of selected cells; it keeps the value…
- Excel: Merge Data From Multiple Cells Into One CellYes. To combine cell contents into one result in Excel for Microsoft 365, use a formula such as…
- Excel Transpose: Turn a List Into a TableTo transpose a row or column in Excel, copy the range, select the destination cell, then choose Home…
- How to Change View with Multiple MonitorsThis guide shows you how to change and control the view across multiple monitors in Windows 10 and…
- Nigerian Wedding Budget Spreadsheet: Costs & SetupA Nigerian wedding budget spreadsheet is a shared, item-by-item plan for what each event will cost, what vendors…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.