Neuron c++ c++11 c++14 c++17 c++

What Is The mt19937 Random Generator In Modern C++?

Random numbers are one of the most important parts of today’s modern programming technologies. They are used in mathematics, physics, in many engineering fields, and in programming such as generating random data for testing, random maps in levels, random trees on a planet – the list is endless. Since C++11, mt19937 (std::mt19937) is implemented as a random number generator. In this post, we explain what mt19937 is and how we can use it. What is a random number and a random number generator in C++? A random number is a number that is randomly chosen in a given range. It is impossible to predict future values based on past or present values and they are uniformly distributed over a defined interval or set. Mersenne prime is a prime number used in mathematics that is a number of the form Mn = 2n − 1 where the n is an integer. The Mersenne Twister is a pseudorandom number generator where the period length is chosen to be a Mersenne Prime. It was developed by Makoto Matsumoto in 1997. Since C++11, the Mersenne Twister mathematical number generator is implemented as a random generator number, it is defined in the header as a std::mersenne_twister_engine that is a random number engine based on Mersenne Twister algorithm. What is the std::mt19937 random number generator in modern C++? In C we use rand(), srand() and in C++ we use std::rand(), std::srand(). While they are added to  to make modern C++ compatible, there are more useful and modern random number generators. These are std::mt19937 and std::mt19937_64. The std::mt1993 is a 32-bit Mersenne Twister by Matsumoto and Nishimura in 1998, and std::mt19937_64 is a 64-bit Mersenne Twister by Matsumoto and Nishimura in 2000. The std::mt19937 is a random number generator defined in the header in C++17 standard and beyond, producing 32-bit pseudo-random numbers by using the Mersenne Twister algorithm with a state size of 19937 bits. This is why it is called mt19937 and there is a 64-bit version called mt19937_64. Both are defined as an instantiation of the mersenne_twister_engine. Now let’s see their definitions. Since C++11, mt19937 is defined as below,   typedef mersenne_twister_engine mt19937;   Since C++11, mt19937_64 is defined as below,   typedef mersenne_twister_engine mt19937_64;   How can we use the random number generator std::mt19937 in modern C++? Simply we can generate modern random number as shown below.   std::mt19937 rnd( std::time(nullptr) );   we can use it like so:   unsigned int r = rnd();   if you want to generate a number in a range you can use modulus operator %.This is how can we generate random number between zero to n, i.e. 0 to 100.   unsigned int r = rnd()%100;   This is how can we generate random number between two numbers, i.e. 50 to 150,   unsigned int r = 50 + rnd()%100;   Is there a simple example to use std::mt19937 in modern C++? Here is a simple example to use std::mt19937.   #include #include #include   int main() { std::mt19937 rnd( std::time(nullptr) );   std::cout

Read More

How To Use void_t Alias Template in C++ 17?

In C++ 17, there is a very useful alias template for metaprogramming that can be used to simplify use of SFINAE. The void_t is a meta-function that is used to map any types ( or types) to type void. In this post, we explain what is void_t, how you can use it in different examples. What is alias template void_t in C++ 17? The void_t is an alias template which is introduced with C++17, it is defined in header and it is a metafunction that is used to map any types (or a sequence of any types) to type void. The main purpose of void_t is to make easy writing of type traits. It is used to solve SFINAE (Substitution Failure Is Not An Error) prior to concepts of C++20 standard. SFINAE rule says that If the deduced type or explicitly specified type for the template parameter fails, the specialization is discarded from the overload set instead of causing an error in compilation. Since C++17, the std::void_t is defined as below.   template using void_t = void;   Now, let’s see how we can use it in template definitions. How to use alias template void_t to check a typename in a template? We can use void_t to if a class has a certain typename using at compile time, here we check if it has ‘type’ typename.   template struct hastype : std::false_type {};   template struct hastype : std::true_type {};   here is a full example about this, here we check ‘typeB‘ typename if it has or not. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28   #include #include   struct stA { typedef int typeA; };   struct stB { typedef int typeB; }; template struct hastype : std::false_type {};   template struct hastype : std::true_type {};   int main() { std::cout

Read More

How To Use std::invoke In C++ 17?

There is a new library feature in the C++17 standard, it is std::invoke which is a useful feature to uniformly invoke callable entities. In this post, we explain what std::invoke is and how we can use it in examples. First, let’s remind ourselves about what is a callable object and what is a functor in modern C++. What is callable object and what is functor in modern C++? A callable object (some call it a functor) is an object that can be used as a function or function pointer by using the operator(). This term is not the same as a function term in programming. We can pass many arguments with them; thus, we don’t need to define many global variables, we can use these kinds of variables in the scope that we use. Here you can find more details about it. What is std::invoke in C++ 17? The std::invoke call is a library feature in C++ 17 that allows invoking a method at run time and improved in C++20 and C++23 with invoke_r. It is defined in the  header and useful to write libraries with the same behavior as the standard’s magic INVOKE rule. You can use std::invoke to call a function or method, a lambda expression, or a member function, or can be used to access a data member, or you can use to invoke a function object. In C++17 it is defined as below,   template std::invoke_result_t     invoke( F&& f, Args&&… args ) noexcept();   In C++20 it is defined as below,   template constexpr std::invoke_result_t     invoke( F&& f, Args&&… args ) noexcept();   And since C++23, there is invoke_r and it is defined as below,   template constexpr R invoke_r( F&& f, Args&&… args ) noexcept();   How can we use std::invoke with a parametric function in C++17? Here is a simple std::invoke example with a parametric function. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18   #include   int myf(int x, int y) { return x*x+y*y; }   int main() { int z = std::invoke(myf, 1, 2);   std::cout

Read More

Learn C++ Optimization With A Genetic Algorithms Example

Solving C++ optimization problems are one of the areas of all quantitative disciplines from social science, economics to engineering fields such as computer science. Genetic Algorithm (GA) is a kind of machine learning process that is used to generate high-quality solutions to optimization and search problems by relying on biologically inspired operators such as mutation, crossover, and selection. In this post, we explain how you can achieve optimization using artificial intelligence techniques. The Genetic Algorithm that we use here below was first mentioned by Željko Kovačević (Embarcadero MVP). Željko has amazing VCL Examples and blog posts about C++ Builder. He gave me this example below as a console app about GA and allowed me to release it free, but credits of this code may require contact with him. Then I improve and simplify (I can’t ofc) it for the C++ Builder and C++ Builder CE. Here, the field and codes below may be harder for beginners but I am sure this post may help how you can develop your scientific applications with C++ Builder CE. What is a Genetic Algorithm? In computer science and research, a Genetic Algorithm (GA) is an algorithm that is used to solve optimization problems by evolving towards better solutions, just as sentient beings do in nature. Genetic Algorithm (GA) is a metaheuristic inspired by the process of natural selection that belongs to the larger class of evolutionary algorithms. Genetic algorithms are commonly used to generate high-quality solutions to optimization and search problems by relying on biologically inspired operators such as mutation, crossover, and selection. In a Genetic Algorithm, first, we create an initial population, then we iterate in a loop by calculating the fitness value, selection, crossover, and mutation steps as below, Genetic Algorithm Schema Genetic Algorithms are one of the older AI/ML methods developed to solve some problems such as solving sudoku puzzles. Genetic Algorithms and Fuzzy Logic were very popular in the 1990s. A typical genetic algorithm requires: A genetic representation of the solution domain, a fitness function to evaluate the solution domain. How to develop a genetic algorithm with C++ Builder? In our optimization example in C++, we develop an optimization algorithm such as Genetic Algorithm about our chosen field. Now let’s explain quickly what we mean by that. First, we have a global Input value that represents a value (number) for which Genetic Algorithm (GA) is trying to find its binary representation.   unsigned int inputValue = 1234567890;   We have individuals to evaluate with genetic algorithms, so we can create this class below. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22   class Individual { public: std::vector gene = std::vector(32); // number of bits unsigned int fitness{ std::numeric_limits::max() };   void evaluate() { unsigned int number = toNumber(); if (number

Read More

What Are The Elementary String Conversions That Come With C++ 17?

In addition to many beneficial features of C++ 17, there are elementary string conversions introduced in that specification. The std::to_chars() and std::from_chars() are defined in header to do conversions between numeric values to strings or strings to numeric values without considering locale-specific conversions. In this post, we explain the std::to_chars() and std::from_chars() that come with C++17. What Are The Elementary String Conversions That Come With C++ 17 ? What is std::to_chars()? The std::to_chars() is defined in header and is used to convert numeric values into a character string within the given valid range. The std::to_chars() is designed to copy the numeric value into a string buffer, with a given specific format, with the only overhead of making sure that the buffer is big enough. You don’t need to consider locale-specific conversions. Here is the syntax of std::to_chars in C++ 17.   std::to_chars_result  to_chars( char* first, char* last, value, int base = 10 );   Here is a simple example.   std::string str= “abcdefgh”; const int ival = 10001000; const auto con = std::to_chars( str.data(), str.data() + str.size(), ival);   In floating point number conversions, std::chars_format types can be used (i.e. std::chars_format::fixed, std::chars_format::scientific, std::chars_format::general,…) What is std::from_chars()? The std::from_chars() is defined in the header and used to convert the string data in a given range to a value (string to int, string to float operations) if no string characters match the pattern or if the obtained value is not representable in a given type of value, then the value has remains unchanged. The std::from_chars() is a lightweight parser that does not need to create dynamic allocation, and you don’t need to consider locale-specific conversions. Here is the syntax of std::from_chars in C++ 17.   std::from_chars_result from_chars( const char* first, const char* last, &value, int base = 10 );   Here is a simple example.   std::string str= “10001000”; int vali; auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), vali);   Is there a full example to elementary string conversions that comes with C++ 17? Here is a full example about std::to_chars() and std::from_chars() in C++ 17. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38   #include #include #include   int main() { std::string str= “abcdefgh”;   // INT TO CHAR const int ival = 10001000; const auto con = std::to_chars( str.data(), str.data() + str.size(), ival);   std::cout

Read More

What Is The Class Template Variant (std::variant) in C++ 17?

In C++ Builder 12, and modern C++ the std::variant is one of the powerful features that comes with C++17. The std::variant is a discriminated union that we can work with multiple data types. It represents a type-safe union and holds one of its types in definition. What is the class template std::variant in C++ 17? The std::variant is a class template defined in  header that represents a disjoint union (or discriminated union). A value of variant contains one of an A, a B, or a C at any one time. It can be used as a multi-type variable, for example, a variable can be a float, an int, or a string. Here is the template definition since C++17:   template class variant;   Here is a simple example that shows how we can use it.   std::variant myvar; myvar = 100; // int   To get value of a variant we can use std::get (std::variant), here is how we can use it:   std::variant myvar2; myvar2 = std::get(myvar);   std::variant has many useful methods and properties that can be used in modern C++, such as index, valueless_by_exception, emplace, swap, get_if, visit, variant_size, variant_size_v, variant_npos, monostate, std::hash, and operators ( =, ==, !=, , =, ) Is there a full example about the class template variant in C++ 17? Here is an example. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23   #include #include #include   int main() { std::variant myvar;   //myvar = true; // bool myvar = 100; // int     if ( std::holds_alternative(myvar) ) std::cout

Read More

What Is The New std::sample Algorithm In C++ 17?

The C++ 17 standard bring us a lot of useful methods, templates and algorithms. One of the great algorithms is std::sample defined in the header that samples at most n elements uniformly from a given range. In this post, we explain the std::sample algorithm and how we can use it with an mt19937 random generator. What is the std::sample algorithm in C++ 17 and beyond? The std::sample algorithm is defined in header that samples at most n elements uniformly from a given range into the output iterator and random numbers can be generated by using a random number generator function. Generally std::mt19937{} is used as random generator and std::random_device{}() is used random generator device. The std::sample algorithm is defined as a template algorithm in C++17 as shown below.   template SampleIterator sample( PopulationIterator first_in, PopulationIterator last_in,                        SampleIterator output, Distance n, URBG&& function );   Here, first_in and last_in are the iterators that defines range of input. n is number of elements to be sampled into output iterator, function is random number generator function. Is there a full example about the std::sample algorithm in C++ 17 and beyond? Here is a full example about std::sample in C++ 17. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28   #include #include #include #include #include #include   int main() { std::vector vec_in {“This”, “LearnCPlusPlus.org”, “is”, “really”, “amazing”,“!”}; std::vector vec_out;   std::cout

Read More

Everything You Need To Know About The Copy Assignment Operator In C++ Classes

Classes and Objects are part of object-oriented methods and typically provide features such as properties and methods. One of the great features of an object orientated language like C++ is a copy assignment operator that is used with operator= to create a new object from an existing one. In this post, we explain what a copy assignment operator is and its types in usage with some C++ examples. What is a copy assignment operator in C++? The Copy Assignment Operator in a class is a non-template non-static member function that is declared with the operator=. When you create a class or a type that is copy assignable (that you can copy with the = operator symbol), it must have a public copy assignment operator. Here is a simple syntax for the typical declaration of a copy assignment operator which is defaulted: Syntax (Since C++11).   class_name & class_name :: operator= ( const class_name& ) = default;   Here is an example in a class.   Tmyclass& operator=(const Tmyclass& other) = default; // Copy Assignment Operator   Is there a simple example of using the copy assignment operator in C++? The forced copy assignment operator is default in any class declarations. This means you don’t need to declare it as above. Let’s give examples without using it. Let’s give a simple C++ example to copy assignment operator with default option, here is a simple class:   class myclass {   public:   std::string str;   };   Because this is default in any class declaration, and it is automatically declared. This class is same as below.   class myclass {   public:   std::string str;     Tmyclass& operator=(const Tmyclass& other) = default; // Copy Assignment Operator };   And here is how you can use this “=” copy assignment operator with both class examples above.   Tmyclass o1, o2;   o2 = o1; // Using Copy Assignment Operator   now let’s see different usage types in C++, 1. Typical Declaration of A Copy Assignment Operator with Swap 2. Typical Declaration of A Copy Assignment Operator ( No Swap) 3. Forced Copy Assignment Operator 4. Avoiding Implicit Copy Assignment 5. Implicitly-declared copy assignment operator 6. Deleted implicitly declared copy assignment operator 7. Trivial copy assignment operator 8. Eligible copy assignment operator 9. Implicitly-defined copy assignment operator C++ Builder is the easiest and fastest C and C++ compiler and IDE for building simple or professional applications on the Windows operating system. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for UIs. There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here.

Read More

What Is The New Optional Class Template In C++ 17?

The C++17 standard came with a lot of great features and std::optional was one of the main features of today’s modern C++. std::optional is a class template that is defined in the header and represents either a T value or no value. In this post, we explain, what is optional in modern C++ and how we can use it efficiently. What is the optional class template in C++ 17 and beyond? The std::optional feature is a class template that is defined in the header and represents either a T value or no value (which is signified by the tag type nullopt_t). In some respects, this can be thought of as equivalent to variant, but with a purpose-built interface. Here is the definition of the std::optional class template.   template class optional;   Optional can be used to define any type of variables as below.   std::optional a(5); std::optional b;   An optional variable can be checked by has_value() method if it has a value or not.   if (a.has_value()) { }   Here is another example that has a function with an optional return.   std::optional testopt(std::string s) { if(s.length()==0) return {}; else return s; }   as you see our function may return a string as an option or it may have no return value. A common use case for optional is the return value of a function that may fail. Any instance of optional at any given point in time either contains a value or does not contain a value. If an optionalcontains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator*() and operator->() are defined. Is there a simple example about the optional class template in C++ 17? Here is a simple example about the std::optional, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19   #include #include   int main() { std::optional a(5);  // a = 5 std::optional b;   // b has no value   if (a.has_value())         { int z = a.value() + b.value_or(0); std::cout

Read More

What Is basic_string_view And string_view In Modern C++

C++17 had enormous changes in C++ features. One of them was basic_string_view (std::basic_string_view) which is a constant string container that can be used for multiple string declarations. The basic_string_view is a modern way of read-only text definition. It can be used by iterators and other methods of the basic_string_view class. In this post, we explain basic_string_view and its types. What is basic_string_view in modern C++ In the Library Fundamentals Technical Specification (LFTS), The C++ commitee introduced std::basic_string_view, and it was approved for C++17. The basic_string_view (std::basic_string_view) is a class template defined in the header that is used to define a constant string container that can be used to define multiple strings which refers to the contiguous character sequence, and the first element of this sequence position at the zero position. The basic_string_view is a modern way of read-only text definition, it can be used by iterators, and other methods of the basic_string_view class can be used.  Here is the syntax of the basic_string_view:   template class basic_string_view;   We can use different character types in std::basic_string_view types as same as std::basic_string. The std::basic_string_view has 5 different string types, these are, std::string_view, std::wstring_view, std::u8string_view, std::u16string_view, and std::u32string_view. The std::string_view provides read-only access to a string definition with chars as similar to the interface of std::string. In addition to this, we can use std::wstring_view, std::u16string_view, and std::u32string_view in C++17. There is std::u8string_view that is added by the C++20 standards too. Here are the basic_string_types and their features. Type Char Type Definition Standard std::string_view char std::basic_string_view (C++17) std::wstring_view wchar_t std::basic_string_view (C++17) std::u8string_view char8_t std::basic_string_view (C++20) std::u16string_view char16_t std::basic_string_view (C++17) std::u32string_view char32_t std::basic_string_view (C++17) Is there an example about basic_string_view in modern C++ Here is a C++ example that we use std::string_view, std::wsting_view, std::u16string_view, std::u32string_view in C++17. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30   #include #include #include   int main() { const std::string_view  sview = “This is a stringview example”; const std::wstring_view wsview = L“This is a stringview example”; const std::u16string_view u16sview = u“This is a stringview example”; const std::u32string_view u32sview = U“This is a stringview example”;   const std::string_view sviews[]{ “This is “, “LearnCPlusPlus.org “, “and welcome “, “!” };   for ( auto sv : sviews) { std::cout

Read More