Operator cpp C

What Is The Integer Sequence (std::integer_sequence) In C++ 14

In modern programming sometimes we want to use a sequence of integers that are created at compile-time. In C++14, the std::integer_sequence is a class template for the sequence of integers that is generated at compile-time. In this post, we explain what integer sequence (std::integer_sequence) is in modern programming. What is the integer sequence (std::integer_sequence) in C++ 14? In C++14, the std::integer_sequence is a class template defined in a header that can be used for the sequence of integers generated at compile-time. In some cases, looping through a range of numbers whose span is unknown is used and, in these cases, we can use the std::integer_sequence integer sequence. Thus, we can create a sequence of integers at compile time. Our application knows the sequence of integers before it runs, and we use them on runtime as a package. In other words, the std::integer_sequence is used to hold a sequence of integers which can be turned into a parameter pack. We can use integer_sequence in template programming or meta-programming algorithms, and this will make our code faster and less complex. In C++14, a simple syntax for the std::integer_sequence can be written as shown below.   template class integer_sequence;   Here, T is the type of integers and val is a parameter pack of integers. Is there a simple integer sequence (std::integer_sequence) example in C++ 14? Here is a simple example how we can use std::integer_sequence.   template void print_sequence2(std::integer_sequence) { ( (std::cout

Read More

What Are The Member Initializers And Aggregates Features in C++14?

C++14 brought us a lot of useful things that we use today. One of the great features of C++14 was the member initializers and aggregates feature that a class with default member initializers may now be an aggregate. In this post, we explain how can use member initializers and aggregates with examples. What are the member initializers and aggregates features in C++14? With the new C++14, a class or struct with default member initializers may now be an aggregate in definition. “If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from its brace-or-equal-initializer or, if there is no brace-or-equal-initializer, from an empty initializer list“. Here is an example,   struct st_X { int a; int b = 100; }; st_X X = { 5 };   Here, X.b will be 100 automatically. Are there simple examples about member initializers and aggregates features in C++14? This feature can be good to be used with default values (i.e. “Unknown”), here is an example.   struct st_student { std::string name; int score; std::string uni = “Unknown”; };   st_student s0 = { “David Millington”}; st_student s1 = { “Yilmaz Yoru”, 98 }; st_student s2 = { “Ian Barker”, 99, “Harvard University” };   Here, David will have 0 score and “Unknown” university, Yilmaz will have “Unknown” university. We can use parameters in the next parameters.   struct st_test {  const char* str; int a; int val = str[a]; }; st_test test = { “ABCD”, 2 };   Here example above, value of test.val is initiated automatically to 67 which is third char ‘C’. Is there a full example about member initializers and aggregates feature in C++14? Here is a full example. 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   #include #include   struct st_student { std::string name; int score; std::string uni = “Unknown”; };   struct st_test {  const char* str; int a; int val = str[a]; };   struct st_X { int a; int b = 100; };   int main() { st_student s0 = { “David Millington”}; st_student s1 = { “Yilmaz Yoru”, 98 }; st_student s2 = { “Ian Barker”, 99, “Harvard University” };   std::cout

Read More

What Are The New Overloads For Ranges In C++ 14?

In C++14, there are pretty good new overloads of std::equal, std::mismatch, and std::is_permutation that can be used to take a pair of iterators for the second range. They can be used with the new C++ Builder 12 along with the 11.x, or 10.x versions too. In this post, we explain these new overloads that we use ranges of iterations. What are the new overloads for ranges in C++ 14? In C++14, there are new overloads of std::equal, std::mismatch, and std::is_permutation that can be used to take a pair of iterators for the second range. We can pass them in two full ranges that have a beginning and end. In modern C++, the range parameter is obtained from a std::list without the original list that needs to be traversed through to get the size. In C++11, std::equal, std::mismatch, and std::is_permutation had 3 parameters, these were First1, Last1 for the Range1 and First2 for the Range2. In C++ 14, there is one more parameter that you can use, it is the Last2 for the Range2. What is the new overload for the std::equal in C++14? In C++11, std::equal is defined as below.   template inline bool equal(_InIt1 _First1, _InIt1 _Last1,_InIt2 _First2)   The std::equal is defined in the header included in the header that returns true if the range between the First1 and Last1 is equal to the range between the First2 and the First2 + (Last1 – First1), and it returns false if this is not satisfied.   std::string s = “abCba”; std::cout

Read More

How Can We Use The is_final Type Trait In C++ 14?

In C++11, the final specifier is used for a function or for a class that cannot be overridden by derived classes, and there was no way to check if that class or method is the final. In C++14, there is a std::is_final type trait that can be used to detect if a class or a method is marked as a final or not. In this post, we explain how we can use the std::is_final type trait in C++14 and C++17. What is the final specifier in modern C++? The final specifier (keyword) is used for a function or for a class that cannot be overridden by derived classes. Regarding virtual overrides, C++11 tends to tighten the rules, to detect some problems that often arise. To achieve this goal C++11 introduced a new contextual keyword, the final specifier. The final keyword specifies that a method cannot be overridden, or a class cannot be derived. If you want to learn more about it, here it is, What is the std::is_final type trait in C++ 14? The std::is_final type trait (UnaryTypeTrait) defined in detects if a class is marked final and returns true or false boolean. If a class or method is final, it returns the member constant value equal to true, if not returns the value is false. Here is the syntax (since C++14).   template struct is_final   How can we use the std::is_final type trait in C++ 14? We can use the std::is_final type trait to check classes if it is marked as a final or not. Here is a simple example.   class myclass final { };   if(  std::is_final::value ) std::cout

Read More

What Are The New Begin End Iterators In C++14?

Iterators are one of the most useful features of containers in modern C++. Mostly we use them with vectors, maps, strings, and other containers of C++. In C++11, the begin() and end() iterators are used to define the start of iteration and the end of the iteration, mostly used in the for loops. In C++14, there are new additions to the global std::begin – std::end functions, and in this post, we explain these new begin-end iterators. What are the begin end iterators in C++11 and beyond? In modern C++, containers are data storage arrays. They are very useful for iterating and searching data with their amazing methods and properties. An iterator () is an object that points to an element in a range of elements (i.e. characters of a string or members of a vector). We can use Iterators to iterate through the elements of this range using a set of operators, for example using the ++, –, and * operators. Iteration can be done with begin/end iterators, The begin() method returns an iterator pointing to the first element in the vector.  The end() method returns an iterator pointing to the theoretical element that follows the last element in the vector. Here is a simple example how we can use begin end iterators in the for iteration as below.   for (auto vi= vec.begin(); vi!= vec.end(); vi++) std::cout

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