Programming dev-c++ FireMonkey FMX ide learn learn

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 Is Heterogeneous Lookup In Associative Containers In C++?

Containers are data storage arrays in modern C++ and they are very useful to iterate and search data with their amazing methods and properties. The C++ Standard Library defines four different main container types and one of them is associative containers such as std::map, and std::set. These class types allow us to use the look-up method “find()” by a value based on a value of that type. C++14 introduced the “Heterogeneous Lookup In Associative Containers” feature that allows the lookup to be done via an arbitrary type, so long as the comparison operator can compare that type with the actual key type. In this post, we explain containers, associative containers, and heterogeneous lookup in associative containers. What is a container in C++? Containers are data storage arrays in modern C++, and they are very useful to iterate and search data with their amazing methods and properties. In C++, there are four main types of containers: Sequence Containers (vectors, arrays, …) Associative Containers (maps, sets, …) Unordered Associative Containers (unordered_set, unordered_map, …) Container Adapters (stack, queue, priority_queue) If you want to know more about containers, here are more details about their types: What are associative containers in C++? Associative Containers are class templates of container types that can be used to implement sorted data structures where can be quickly searched. They are sorted by keys. We can say they are about O(log n) complexity data structures. The associative containers are: std::map : a class template for the collection of key-value pairs, its keys are unique and it is sorted by keys std::set : a class template for the collection of unique keys, it is sorted by keys  multiset : a class template for the collection of keys, it is sorted by keys multimap : a class template for the collection of key-value pairs, it is sorted by keys  What is heterogeneous lookup in associative containers in C++? The C++ Standard Library defines 4 associative container types. These class types allow us to use the look-up method find() by a value based on a value of that type. C++14 introduced the “Heterogeneous Lookup In Associative Containers” feature that allows the lookup to be done by an arbitrary type, so the comparison operator can compare types with the actual key type. The heterogeneous lookup in associative containers gives us to use std::map, std::set, and other associative containers. In example, let’s have some strings and have some values in a std::map (which is a associative container),   std::map mymap { { “Hello Developers”, 10 }, { “Please Visit Us”, 20 }, { “LearnCPlusPlus.org”, 30 } };   we can use find method of map as shown below:   auto m = mymap.find(std::string(“LearnCPlusPlus.org”)); // m iterator   In the heterogeneous lookup we can use less or other features. Is there a full example about heterogeneous lookup in associative containers in C++? When we want to do heterogeneous lookup, all we have to do is to use std::less or other heterogeneous lookup features and we should implement correct comparison methods. Here is an example,   std::map mymap2 { { “Hello Developers”, 10 }, { “Please Visit Us”, 20 }, { “LearnCPlusPlus.org”, 30 } };   The interesting thing is, it is straightforward to enable and we can use find method like so:   auto m = mymap2.find(std::string(“LearnCPlusPlus.org”)); // m iterator   Note that here m […]

Read More

What Are Integral_constant And () Operator In C++?

Modern C++ has base class features that can be used with other modern features of C++. The std::integral_constant is the base class for the C++ type traits in C++11, and in C++14, std::integral_constant gained an operator () overload to return the constant value. In this post, we explain what integral_constant and () operator are in C++14. What is integral_constant in C++? The std::integral_constant  is the base class for the C++ type traits in header that wraps a static constant of specified type. The behavior in a code part that adds specializations for std::integral_constant is undefined. Here is the definition in header since C++11,   template struct integral_constant;   Here is a very simple example to how can we use std::integral_constant, in C++11 we can use ::value to retrieve its value,   typedef std::integral_constant five;   std::cout

Read More

What Are The Standard User-Defined Literals In C++14?

C++11 introduced new forms of literals using modified syntax and semantics to provide User-Defined Literals (UDL) also known as Extensible Literals. While there was the ability to use them the standard library did not use any of them. In C++14, the commission added some standard literals. In this post, we explain user-defined literals operators and we explain some of these standard literals added in C++14. What are the user defined literal operators in C++? C++11 introduced new forms of literals using modified syntax and semantics in order to provide User-Defined Literals (UDL) also known as Extensible Literals. Using user-defined literals, user-defined classes can provide new literal syntax and they can be used with the operator “” to combine values with conversion operators. Here below, we explain how to use user-defined literals in C++. What are the standard user-defined literals in C++14? In C++14, we have some standard user-defined literal operators that comes with standard library. These are literals for basic strings, for chrono types, and for complex number types. We can access to these operators by: using namespace std::literals; using namespace std::string_literals; using namespace std::literals::string_literals; C++14 adds the following standard literals below, For the string types there is an operator”” s() for basic string, s : std::basic_string types for creating the various string types std::string, std::wstring, etc. here how we can use it with auto,   auto str = “LearnCPlusPlus.org”s; // auto deduction to string   Suffixes for std::chrono::duration values, h : hour type for the std::chrono::duration time intervals m : minute type for the std::chrono::duration time intervals s : second type for the std::chrono::duration time intervals ms : millisecond type for the std::chrono::duration time intervals ns : nanosecond type for the std::chrono::duration time intervals us : u.second type for the std::chrono::duration time intervals here how we can use them with auto,   auto durh = 24h;            // auto deduction to chrono::hours auto durm = 60min;            // auto deduction to chrono::minutes auto durs = 120s;            // auto deduction to chrono::seconds auto durms = 1000ms;         // auto deduction to chrono::milliseconds auto durns = 2000ns;         // auto deduction to chrono::nanoseconds   Suffixes for complex number literals, if : imaginary number for the std::complex types i : imaginary number for the std::complex types il : imaginary number for the std::complex types here how we can use them with auto,   auto zi   = 5i;             // auto deduction to complex auto zif  = 7if;             // auto deduction to complex auto zil  = 9il;             // auto deduction to complex   there are more definitions. Is there a full example of how to use standard user-defined literals in C++14? Here is a full example about standard user-defined literals in C++. 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   #include #include #include #include #include   using namespace std::literals; using namespace std::string_literals; // using namespace std::literals::string_literals;   int main() { auto str = “LearnCPlusPlus.org”s; // auto deduction to string   auto durh = 24h;            // auto deduction to chrono::hours auto durm = 60min;            // auto deduction to chrono::minutes auto durs = 120s;            // auto deduction to chrono::seconds auto durms = 1000ms;         // auto deduction to chrono::milliseconds auto durns = 2000ns;         // auto deduction to chrono::nanoseconds   auto zi   = 5i;             // auto deduction to complex auto zif  = 7if;             // auto deduction to complex auto zil  = 9il;             // auto deduction to complex   }   For more information about the standard user-defined literals, please […]

Read More

How To Use Tuple Addressing Via Type In C++14 And Beyond

The tuple ( std::tuple ) is a class template that stores the different types of elements, it also supports empty lists in modern C++. This template was introduced in C++11 and improved in C++14. In this post, we explain tuple addressing via type features that come with the C++14 standard. What is std::tuple in C++? The tuple ( std::tuple) is a class template a fixed-size collection of different types of values like floats, integers, texts, etc. and it is defined in the tuple header. In another term tuple stores the different types of elements, it also supports empty lists. This template has been available since C++11 and improved in C++14, and C++20 standards. In C++ programming, the std::tuple is a generalization of std::pair. The destructor of the tuple is trivial if std::is_trivially_destructible::value is set to true for every type in Types. What is the syntax for std::tuple in C++? Here is the syntax of std::tuple in C++,   template class tuple;   Is there a C++ std::tuple example, how can we use tuples? Here is a example to define different types of members in a my_tuple,   std::tuple my_tuple { “text one”, 9, 2.22, “text two”, 15 , 7.88, “text three”};   std::cout

Read More

Learn About Useful Shared Mutexes Locking In Modern C++

A concurrency support library is designed to solve problems in modern C++ that arise with multi-thread development. This library includes built-in support for threads (std::thread), atomic operations (std::atomic), mutual exclusion (std::mutex), condition variables (std::condition_variable), and many other features. In C++14, in addition to mutex, there is a shared_mutex which is an instance of the class located in header. In this post, we explain using shared mutexes locking in Modern C++. What is a mutex (mutual exclusion) in C++? Mutual Exclusion is a property of concurrency control and in programming, the Mutual Exclusion is a data exclusion method to lock and unlock data that provides exclusive access to a resource. This is mostly needed when we use shared data in multi-thread and multi-task operations in parallel programming. In C++, we can use std::mutex to define mutex data variables to protect his shared data from being simultaneously accessed by multiple threads. Here is an example of how we can use std::mutex with its lock() and unlock() methods,   std::mutex mtx;   mtx.lock();   // do operations mtx.unlock();   What is a shared mutex in modern C++? The shared mutex comes with C++14, it is an instance of the class located in header and used with the shared_mutex class name in mutual exclusion operations of threads. The shared_mutex class is a part of the thread support library, it is a synchronization primitive for the thread operations that can be used to protect shared data when multiple threads try to access. Here is how we can define a shared mutex by using std::shared_mutex.   std::shared_mutex ;   Is there an example about shared mutexes (std::shared mutex)? Here is a simple example about std::shared_mutex with its try_lock_shared() and unlock_shared() methods that comes with C++17.   std::shared_mutex sharedmutex;   // in a thread function sharedmutex.try_lock_shared(); // do operations sharedmutex.unlock_shared();   How to use shared lock unlock mutexes methods? A shared_mutex has lock() and unlock() methods as in mutex type, In C++17, it is improved and supports the additional methods lock_shared, unlock_shared, and try_lock_shared. Simply these are: lock_shared (C++17) The lock_shared method is used to block the calling thread until the thread obtains shared ownership of the mutex. unlock_shared (C++17) The unlock_shared method is used to release shared ownership of the mutex held by the calling thread. try_lock_shared (C++17) The try_lock_shared method is used to obtain shared ownership of the mutex without blocking. Return type is can be  true if the method obtains ownership, or false if it cannot. Is there a full example of how to use shared mutexes (std::shared mutex) in C++? Let’s assume that we have a global val and we read data by a getv() and we write data by putv() functions, and we run these functions in threads. Here is a full and simple example about shared mutexes (std::shared mutex). 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 39 40 41 42 43   #include #include #include #include   std::shared_mutex sharedmutex;   int val=500;   void putv( int v ) {   sharedmutex.lock();   std::this_thread::sleep_for(std::chrono::microseconds(2));  //some latency simulation val = v;   sharedmutex.unlock(); }   void getv( int &v ) {   sharedmutex.lock_shared();   std::this_thread::sleep_for(std::chrono::microseconds(2));  // some latency simulation   v = val;   sharedmutex.unlock_shared(); }     int main() {   int readval;   std::thread t1( getv , std::ref( readval ) );   std::thread t2( putv , 100); […]

Read More

What Are The Amazing Containers In Modern C++?

Containers are powerful data storage arrays in modern C++ and they are very useful to iterate and search data with their amazing methods and properties. The C++ Standards library defines 4 container types. In this post, we explain containers in modern C++. What is a container in modern C++? Containers are modern data storage arrays in modern C++ and they are very useful to iterate and search data with their amazing methods and properties. A container is a holder object that stores data elements (a collection of data objects). They are implemented as a class template to define objects that can be used with modern rules of C++ (The rule of 6), they allow great flexibility in the different data types supported as elements, they can be used with int, float, double, etc. or with struct types, they can be used with other modern types of C++, lambdas and templates. Thus, the developer can create different data sets in memory, these can be static or dynamic, they are safe and optimized well. Basically, a container manages the storage space for its elements and provides properties and methods to access and operate on them, these methods and properties can be either directly or through iterators. They are mostly dynamic data structures, and they are well optimized for the memory management and performance. In C++, there are four main types of containers, Sequence Containers (vectors, arrays, …) Associative Containers (maps, sets, …) Unordered Associative Containers (unordered_set, unordered_map, …) Container Adapters (stack, queue, priority_queue) Now, let’s see each of them. What are sequence containers in modern C++? In C++, the Sequence Containers are class templates of container types of modern C++ that can be used to implement data structure types (vector, array,…) where they can be accessed sequentially. They are a kind of data types, but objects of classes and they can use methods of its classes, optimized for many modern C++ algorithms and methods. The sequence containers are; std::array : a class template for the static contiguous array (modern C array) std::vector : a class template for the dynamic contiguous array ( modern dynamic C arrays) std::deque : a class template for the double-ended queue std::list : a class template for the doubly-linked list (modern linked list) std::forward_list : a class template for the singly-linked list (modern linked list) What are sequence containers in modern C++? Associative Containers are class templates of container types that can be used to implement sorted data structures where can be quickly searched. They are sorted by keys. We can say they are about O(log n) complexity data structures. The associative containers are; std::map : a class template for the collection of key-value pairs, its keys are unique and it is sorted by keys std::set : a class template for the collection of unique keys, it is sorted by keys  multiset : a class template for the collection of keys, it is sorted by keys multimap : a class template for the collection of key-value pairs, it is sorted by keys  What are associative containers in modern C++? Unordered Associative Containers are class templates of container types that can be used to implement unsorted (hashed) data structures where they can be quickly searched. They are about O(1) amortized, O(n) worst-case complexity data structures. The unsorted associative containers are; unordered_set : a class template for […]

Read More