codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › C++ how to: random numbers

C++ how to: random numbers

Use the random library.

Modern way: a mt19937 engine seeded by random_device and a distribution.

Example code

#include <iostream>
#include <random>
using namespace std;
int main() {
  random_device rd;
  mt19937 gen(rd());
  uniform_int_distribution<int> dice(1, 6);
  cout << dice(gen) << endl;
  return 0;
}

Run this code in the online editor

← C++ how to: add two numbersLive project: Bank account (OOP) →