std::mt19937 Class in C++
Last Updated :
30 Mar, 2021
std::mt19937(since C++11) class is a very efficient pseudo-random number generator and is defined in a random header file. It produces 32-bit pseudo-random numbers using the well-known and popular algorithm named Mersenne twister algorithm. std::mt19937 class is basically a type of std::mersenne_twister_engine class.
typedef mersenne_twister_engine<uint_fast32_t,
32,624,397,31,0x9908b0df,11,0xffffffff,7,0x9d2c5680,15,0xefc60000,18,1812433253>
mt19937;
Syntax :
mt19937 mt1(seed_value);
Here mt1 is an instance of the mt19937 class and it takes a seed value to generate an entire sequence.
Significance Of The Name mt19937
mt19937 stands for mersenne twister with a long period of 219937 – 1 which means mt19937 produces a sequence of 32-bit integers that only repeats itself after 219937 – 1 number have been generated.
Similarities Between mt19937 And rand() & srand():
The std::mt19937 does two things –
- When an std::mt19937 object is instantiated, it takes an argument which is used to generate seed value(like srand()).
- By using operator(), it generates a random number (like rand()).
Below is the example to demonstrate the similarities:
C++
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main()
{
mt19937 mt( time (nullptr));
cout << mt() << '\n' ;
return 0;
}
|
Being a type of std::mersenne_twister_engine class it has the same member functions which mersenne_twister_engine does. Here is the list of some important member functions –
1. (constructor): constructs the mt19937 object. It takes either a seed value of result type or a seed sequence object(Similar to srand() function).
Example :
C++
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main()
{
mt19937 mt( time (nullptr));
cout << mt() << '\n' ;
return 0;
}
|
2. min(): returns the minimum value operator() can return (which is zero).
Example:
C++
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main()
{
mt19937 mt( time (nullptr));
cout << "the minimum integer it can generate is " <<
mt.min() << endl;
return 0;
}
|
Output
the minimum integer it can generate is 0
3. max(): returns maximum value operator() can return ( which is 232 – 1 = 4294967295 )
Example :
C++
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main()
{
mt19937 mt( time (nullptr));
cout << "mt19937 can generate random numbers upto " <<
mt.max() << endl;
return 0;
}
|
Output
mt19937 can generate random numbers upto 4294967295
4. seed(): reinitializes the seed value of the object either by taking a seed value of result type or by taking a seed sequence object.
Example :
C++
#include <iostream>
#include <random>
using namespace std;
int main()
{
mt19937 mt;
mt.seed(45218965);
cout << "some random numbers generated by mt19937 are:" <<
endl;
for ( int i = 5; i > 0; i--)
{
cout << mt() << ' ' ;
}
return 0;
}
|
Output
some random numbers generated by mt19937 are:
3334444225 240363925 3350157104 146869560 639267854
5. operator(): it generates pseudo-random integers.(similar to rand() function).
Example:
C++
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main()
{
mt19937 mt( time (nullptr));
for ( int i = 0; i < 5; i++)
{
cout << mt() << ' ' ;
}
return 0;
}
|
Output
3529725061 3019704141 2006641117 725527349 3631905871
There are also non-member functions overloaded to work with std::mt19937 object. These are –
- operator<<() – This is overloaded so that we can directly print the value generated by the mt19937 object to the output stream.
- operator>>() – it is used to extract seed value from input.
Here is a simple example to generate a pseudo-random number by taking a seed value from the user –
Using operator<<() and operator>>() :
Example :
C++
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main()
{
mt19937 mt;
cout << "enter a integer to begin" <<
endl;
cin >> mt;
cout << "a random number " <<
mt() << " is generated" ;
return 0;
}
|
Output
enter a integer to begin
a random number 3499211612 is generated
Why Use mt19937 Instead Of rand() ?
Although the rand() function can be used in a small range, it is inefficient for generating real-world like random numbers. A careful person can observe the repetitions of the random numbers generated by rand() which is very risky. Whereas std::mt19937 has the following advantages –
- It has a very long period compared to the rand(). It will take a longer time. If an implementation of the Mersenne twister could generate 1,000,000,000 (one billion) pseudo-random numbers every second, a program that generated pseudo-random numbers would need to run about 1.3684 × 105,985 years to repeat the random sequence. So it is safe to assume that an observer will never guess the number.
- Many random number generators can be initiated simultaneously with different seed values. Here is an example –
C++
#include <iostream>
#include <random>
using namespace std;
int main()
{
mt19937 mt1(10000);
mt19937 mt2(100000);
cout << mt1() << endl;
cout << mt2() << endl;
return 0;
}
|
Output
2342776460
1235064505
Similar Reads
std::fstream::close() in C++
Files play an important role in programming. It allows storage of data permanently. The C++ language provides a mechanism to store the output of a program in a file and browse from a file on the disk. This mechanism is termed file handling. In order to perform file handling, some general functions w
4 min read
class std::string_view in C++17
The std::string has some demerits, one of the most common situations is constant strings. Below is the program that demonstrates the problem that occurs in dealing with constant strings with std::string: Program 1: C/C++ Code // C++ program to demonstrate the // problem occurred in string #include
12 min read
How to Create a Template Class in C++?
In C++, template classes are used to create generic classes that can work for different data types. In this article, we will learn how to create a template class in C++. Create a Template Class in C++ To create a template class in C++, we can follow the below syntax: Syntax of Template Classtemplate
2 min read
Classes vs Structure vs Union in C++
Class: It is a user-defined datatype enclosed with variables and functions. It is like a blueprint for an object. Class members are private by default. For Example, the car is an object, its color, design, weight are its attributes whereas the brake, speed limit, etc. are its functions. Syntax: clas
4 min read
std::chrono::day in C++ 20
In C++, the <ctime> header provides the std::chrono::day class that represents a day in the given month. In this article, we will learn how to use the std::chrono::day class in C++. std::chrono::day in C++ The std::chrono::day class was introduced in C++ 20 to represent a day in a month. It is
2 min read
How to Declare a Stack in C++?
In C++, Stacks are a type of container adaptor with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. In this article, we will learn how to declare a stack in C++. Declaring a Stack in C++ STLThe C++ STL provides a co
2 min read
Helper Function in C++ Classes
In C++, the users can keep their class methods organized and readable with the help of private helper functions. Helper functions are utility functions that are only accessible within the class. They can't be called externally but can be used by the class's public methods to perform lower-level task
3 min read
Expression must have class type error in C++
The expression must have class type is an error that is thrown when the dot(.) operator is used to access an object's properties, is used on pointers to objects. Dot('.') Operator is basically used for accessing the fields and methods of an object, but when a dot operator is used on the pointer to o
2 min read
Calculator using Classes in C++
Implementing a calculator in C++ using the concept of the classes. Functions: Addition of two numbers.Difference between two numbers.Product of two numbers.Division of two numbers. Approach: Declare local variables a, b for two numeric values.Enter the Choice.Takes two numbers, a and b.do-while jump
2 min read
Program to create Custom Vector Class in C++
The task is to implement a custom vector class similar to the STL vector with following functions: int push_back(data): adds an element(of any data_type) to the end of array and also returns the number of elements in that vectordata_type pop_back(): removes an element from the end of array, also ret
5 min read