PrevUpHomeNext

c++ random number: std::mt19937


c++ random number - Posted on Oct 20, 2024 - See https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine/mersenne_twister_engine - Logs Home - d0036

c++ random number generator std::mt19937

std::random_device

#include <random>
#include <iostream>

int main()
{
	std::random_device rd;
	unsigned int number = rd();
	std::cout << number << std::endl;
}

std::mt19937

Any c++ integer value can be used as a seed.

Use the number generated from std::random_device object as a seed.

#include <random>
#include <iostream>

int main()
{
	unsigned int seed = std::random_device{}();
	std::mt19937 gen{seed};
	unsigned long int number = gen();
	std::cout << number << std::endl;
}

Use Auto deduced

#include <random>
#include <iostream>

int main()
{
	auto gen = std::mt19937{std::random_device{}()};
	auto number = gen();
	std::cout << number << std::endl;
}

cpp/c++

c++ std::exception:

std::cout.write(err.data(), err.size());

std::cout << std::endl;

caught:

  ===================================
  #  The c++ programming language.  #
  #                                 #
  #  Join c++ Discord: yZcauUAUyC   #
  #  Deck                           #
  ===================================

Home: cppfx.xyz

K


PrevUpHomeNext