Random Numbers C++17

Hello!!

It’s been a while that I have posted something here…. Today I was reading new C++ book with 2017 standards. It’s amazing how fast things been changing in C++ and it’s evolving quickly.

Even-though changing the habit is hard, I like where C++ is going to.

Here is an example of Generating Random Numbers in C++17 Standards:

/*
 */

#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>     /* srand, rand */
#include <time.h> 
#include <algorithm>
#include <random>

using namespace std;
int main(int argc, char** argv) {
    
    vector<int> x;
    
                random_device rd{};
        //engine and init with random seeds
	auto mtgen = std::mt19937{ rd() };
	auto ud = std::uniform_int_distribution<>{ 1,100 };   //old way  -> rand()%10+ 1 -> range from 1 to 10
	for (auto i = 0; i < 20; i++)
	{
		auto number = ud(mtgen);
		x.push_back(number);
	}
    
    
    std::cout << "Normal Order: " << endl;
    
    for(auto &y: x)
    {
        cout << y << endl;;
    }
    
    cout << "Reverse order:" << endl;
    
    std::reverse(x.begin(), x.end());
    
    for(auto &z: x)
    {
        cout << z<< endl;
    }
    std::sort(x.begin(), x.end());
    
    cout << "Sorted order:" << endl;

   for(auto &z: x)
    {
        cout << z<< endl;
    }

    return 0;
}

 

In addition, if you are curious about the book I am reading here is the link to it; It’s great book and I would highly recommend it.

Modern C++ Programming Cookbook

All the best 🙂 

– Saeed



BTC: bc1qrxmjgsc5a2fwn7zplpcu7665uq39tp2ss7luwk

Comments are closed.