Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

C++ > Code Snippets Code Examples

Use a reverse_iterator to go from the end to the beginning

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
/* Use a reverse_iterator to go from the end to the beginning */ #include <iostream> #include <list> #include <algorithm> #include <string> using namespace std; static const int ARRAY_SIZE = 5; int main( ) { list<string> lstStr; lstStr.push_back("A"); lstStr.push_back("B"); lstStr.push_back("C"); lstStr.push_back("D"); for (list<string>::iterator p = lstStr.begin( ); p != lstStr.end( ); ++p) { cout << *p << endl; } for (list<string>::reverse_iterator p = lstStr.rbegin( ); p != lstStr.rend( ); ++p) { cout << *p << endl; } } /* A B C D D C B A */
Iterators in C++ Language
Iterators are just like pointers used to access the container elements. Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container. They allow you to iterate over the container, access and assign the values, and run different operators over them, to get the desired result.
Syntax for Iterators in C++
<ContainerType> :: iterator; <ContainerType> :: const_iterator;
• Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used. • Iterators provide a generic approach to navigate through the elements of a container. Operator (*) : The '*' operator returns the element of the current position pointed by the iterator. Operator (++) : The '++' operator increments the iterator by one. Therefore, an iterator points to the next element of the container. Operator (==) and Operator (!=) : Both these operators determine whether the two iterators point to the same position or not. Operator (=) : The '=' operator assigns the iterator. Iterators can be smart pointers which allow to iterate over the complex data structures. A Container provides its iterator type. Therefore, we can say that the iterators have the common interface with different container type. The container classes provide two basic member functions that allow to iterate or move through the elements of a container: begin(): The begin() function returns an iterator pointing to the first element of the container. end(): The end() function returns an iterator pointing to the past-the-last element of the container. Input Iterator: An input iterator is an iterator used to access the elements from the container, but it does not modify the value of a container. Operators used for an input iterator are: Increment operator(++), Equal operator(==), Not equal operator(!=), Dereference operator(*). Output Iterator: An output iterator is an iterator used to modify the value of a container, but it does not read the value from a container. Therefore, we can say that an output iterator is a write-only iterator. Operators used for an output iterator are: Increment operator(++), Assignment operator(=). Forward Iterator: A forward iterator is an iterator used to read and write to a container. It is a multi-pass iterator. Operators used for a Forward iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=). Bidirectional iterator: A bidirectional iterator is an iterator supports all the features of a forward iterator plus it adds one more feature, i.e., decrement operator(--). We can move backward by decrementing an iterator. Operators used for a Bidirectional iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=), Decrement operator(--). Random Access Iterator: A Random Access iterator is an iterator provides random access of an element at an arbitrary location. It has all the features of a bidirectional iterator plus it adds one more feature, i.e., pointer addition and pointer subtraction to provide random access to an element. Following are the disadvantages of an iterator: • If we want to move from one data structure to another at the same time, iterators won't work. • If we want to update the structure which is being iterated, an iterator won?t allow us to do because of the way it stores the position. • If we want to backtrack while processing through a list, the iterator will not work in this case. Following are the advantages of an iterator: • Ease in programming: It is convenient to use iterators rather than using a subscript operator[] to access the elements of a container. If we use subscript operator[] to access the elements, then we need to keep the track of the number of elements added at the runtime, but this would not happen in the case of an iterator. • Code Reusability: A code can be reused if we use iterators. In the above example, if we replace vector with the list, and then the subscript operator[] would not work to access the elements as the list does not support the random access. However, we use iterators to access the elements, then we can also access the list elements. • Dynamic Processing: C++ iterators provide the facility to add or delete the data dynamically.
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
/* Iterators in C++ language */ // C++ code to demonstrate the working of next() and prev() #include<iostream> #include<iterator> // for iterators #include<vector> // for vectors using namespace std; int main() { vector<int> ar = { 1, 2, 3, 4, 5 }; // Declaring iterators to a vector vector<int>::iterator ptr = ar.begin(); vector<int>::iterator ftr = ar.end(); // Using next() to return new iterator // points to 4 auto it = next(ptr, 3); // Using prev() to return new iterator // points to 3 auto it1 = prev(ftr, 3); // Displaying iterator position cout << "The position of new iterator using next() is : "; cout << *it << " "; cout << endl; // Displaying iterator position cout << "The position of new iterator using prev() is : "; cout << *it1 << " "; cout << endl; return 0; }
Static Keyword in C++
Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime. In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C++, static can be field, method, constructor, class, properties, operator and event. Advantage of C++ static keyword: Memory efficient. Now we don't need to create instance for accessing the static members, so it saves memory. Moreover, it belongs to the type, so it will not get memory each time when instance is created. C++ Static Field: A field which is declared as static is called static field. Unlike instance field which gets memory each time whenever you create object, there is only one copy of static field created in the memory. It is shared to all the objects. It is used to refer the common property of all objects such as rateOfInterest in case of Account, companyName in case of Employee etc. Static variables inside functions: Static variables when used inside function are initialized only once, and then they hold there value even through function calls. These static variables are stored on static storage area , not in stack.
void counter() { static int count=0; cout << count++; } int main(0 { for(int i=0;i<5;i++) { counter(); } }
Static class objects: Static keyword works in the same way for class objects too. Objects declared static are allocated storage in static storage area, and have scope till the end of program. Static objects are also initialized using constructors like other normal objects. Assignment to zero, on using static keyword is only for primitive datatypes, not for user defined datatypes.
class Abc { int i; public: Abc() { i=0; cout << "constructor"; } ~Abc() { cout << "destructor"; } }; void f() { static Abc obj; } int main() { int x=0; if(x==0) { f(); } cout << "END"; }
Static data member in class: Static data members of class are those members which are shared by all the objects. Static data member has a single piece of storage, and is not available as separate copy with each object, like other non-static data members. Static member variables (data members) are not initialied using constructor, because these are not dependent on object initialization. Also, it must be initialized explicitly, always outside the class. If not initialized, Linker will give error.
class X { public: static int i; X() { // construtor }; }; int X::i=1; int main() { X obj; cout << obj.i; // prints value of i }
Static member functions: These functions work for the class as whole rather than for a particular object of a class. It can be called using an object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator.
class X { public: static void f() { // statement } }; int main() { X::f(); // calling member function directly with class name }
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
/* static keyword has different meanings when used with different types simple code example */ // CPP program to illustrate class objects as static #include<iostream> using namespace std; class Happy { int i = 0; public: Happy() { i = 0; cout << "Inside Constructor\n"; } ~Happy() { cout << "Inside Destructor\n"; } }; int main() { int x = 0; if (x==0) { static Happy obj; } cout << "End of main\n"; }
List Library push_back() Function in C++
Add element at the end. Adds a new element at the end of the list container, after its current last element. The content of val is copied (or moved) to the new element. This effectively increases the container size by one. The list:push_back() function in C++ STL is used to add a new element to an existing list container. It takes the element to be added as a parameter and adds it to the list container.
Syntax for List push_back() Function in C++
#include <list> void push_back (const value_type& val); void push_back (value_type&& val);
val
Value to be copied (or moved) to the new element. Member type value_type is the type of the elements in the container, defined in list as an alias of its first template parameter (T). This function accepts a single parameter which is mandatory value. This refers to the element needed to be added to the list, list_name. This function does not return any value. The storage for the new elements is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
Complexity
Constant
Iterator validity
No changes
Data races
The container is modified. No existing contained elements are accessed: concurrently accessing or modifying them is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container. If allocator_traits::construct is not supported with val as argument, it causes undefined behavior.
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
/* list::push_back() function is used to push elements into a list from the back. The new value is inserted into the list at the end, after the current last element and the container size is increased by 1.*/ // CPP program code example to illustrate application Of push_back() function #include <iostream> #include <list> using namespace std; int main() { list<int> mylist{}; mylist.push_back(7); mylist.push_back(89); mylist.push_back(45); mylist.push_back(6); mylist.push_back(24); mylist.push_back(58); mylist.push_back(43); // list becomes 7, 89, 45, 6, 24, 58, 43 // Sorting function mylist.sort(); for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; }
List Library rend() Function in C++
Return reverse iterator to reverse end. Returns a reverse iterator pointing to the theoretical element preceding the first element in the list container (which is considered its reverse end). The C++ list::rend function returns the reverse iterator pointing to the element preceding the first element (reversed past-the-last element) of the list. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the list container. Similarly, decreasing a reverse iterator results into moving to the end of the list container. The range between list::rbegin and list::rend contains all the elements of the container (in reverse order).
Syntax for List rend() Function in C++
#include <list> reverse_iterator rend() nothrow; const_reverse_iterator rend() const nothrow;
No parameter is required. Function returns a reverse iterator to the reverse end of the sequence container. If the list object is const-qualified, the function returns a const_reverse_iterator. Otherwise, it returns a reverse_iterator. Member types reverse_iterator and const_reverse_iterator are reverse bidirectional iterator types (pointing to an element and to a const element, respectively). See list member types.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
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
/* list::rend() is an built-in function in C++ STL which is declared in header file. rend() is a reverse end function. rend() returns a reverse iterator which is pointing to the position before the first element of the list container associated. Reverse iterator is an iterator which moves in reverse direction, starting from the end and will move towards the start. However back() also returns the last element but unlike the simple iterator this bidirectional iterator moves in backward direction. */ /* Return reverse iterator to reverse end by list rend() function code example */ #include <iostream> #include <list> using namespace std; int main (){ list<string> MyList{"Alpha","Coding","Skills"}; list<string>::reverse_iterator rit; rit = MyList.rend(); rit--; cout<<*rit<<" "; rit--; cout<<*rit<<" "; rit--; cout<<*rit<<" "; return 0; }
Iterator Library reverse_iterator in C++
This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. A copy of the original iterator (the base iterator) is kept internally and used to reflect the operations performed on the reverse_iterator: whenever the reverse_iterator is incremented, its base iterator is decreased, and vice versa. A copy of the base iterator with the current state can be obtained at any time by calling member base. Notice however that when an iterator is reversed, the reversed version does not point to the same element in the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element (this would be the past-the-end element of the reversed range).
Syntax for reverse_iterator in C++
#include <iterator> template <class Iterator> class reverse_iterator;
Iterator
A bidirectional iterator type. Or a random-access iterator, if an operator that requires such a category of iterators is used.
Member types
• iterator_type Iterator Iterator's type • iterator_category iterator_traits<Iterator>::iterator_category Preserves Iterator's category • value_type iterator_traits<Iterator>::value_type Preserves Iterator's value type • difference_type iterator_traits<Iterator>::difference_type Preserves Iterator's difference type • pointer iterator_traits<Iterator>::pointer Preserves Iterator's pointer type • reference iterator_traits<Iterator>::reference Preserves Iterator's reference type
Member functions
• (constructor) Constructs reverse_iterator object (public member function ) • base Return base iterator (public member function ) • operator* Dereference iterator (public member function ) • operator+ Addition operator (public member function ) • operator++ Increment iterator position (public member function ) • operator+= Advance iterator (public member function ) • operator- Subtraction operator (public member function ) • operator-- Decrease iterator position (public member function ) • operator-= Retrocede iterator (public member function ) • operator-> Dereference iterator (public member function ) • operator[] Dereference iterator with offset (public member function )
Non-member function overloads
• relational operators Relational operators for reverse_iterator (function template ) • operator+ Addition operator (function template ) • operator- Subtraction operator (function template )
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
/* std::reverse_iterator is an iterator adaptor that reverses the direction of a given iterator. In other words, when provided with a bidirectional iterator, std::reverse_iterator produces a new iterator that moves from the end to the beginning of the sequence defined by the underlying bidirectional iterator. */ /* Constructs reverse_iterator object by std::reverse_iterator */ #include <iostream> #include <iterator> template<typename T, size_t SIZE> class Stack { T arr[SIZE]; size_t pos = 0; public: T pop() { return arr[--pos]; } Stack& push(const T& t) { arr[pos++] = t; return *this; } // we wish that looping on Stack would be in LIFO order // thus we use std::reverse_iterator as an adaptor to existing iterators // (which are in this case the simple pointers: [arr, arr+pos) auto begin() { return std::reverse_iterator(arr + pos); } auto end() { return std::reverse_iterator(arr); } }; int main() { Stack<int, 8> s; s.push(5).push(15).push(25).push(35); for(int val: s) { std::cout << val << ' '; } }
List Library end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the list container. The past-the-end element is the theoretical element that would follow the last element in the list container. It does not point to any element, and thus shall not be dereferenced. Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with list::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as list::begin.
Syntax for List end() Function in C++
#include <list> iterator end() noexcept; const_iterator end() const noexcept;
This function does not accept any parameter. Function returns an iterator to the element past the end of the sequence. If the list object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are bidirectional iterator types (pointing to an element and to a const element, respectively). The list::end() is a built-in function in C++ STL which is used to get an iterator to past the last element. By past the last element it is meant that the iterator returned by the end() function return an iterator to an element which follows the last element in the list container. It can not be used to modify the element or the list container.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
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
/* returns a random access iterator which points to the last element of the list by std::list::end() function code example */ // CPP program to illustrate the list::end() function #include <bits/stdc++.h> using namespace std; int main() { // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // using end() to get iterator // to past the last element list<int>::iterator it = demoList.end(); // This will not print the last element cout << "Returned iterator points to : " << *it << endl; // Using end() with begin() as a range to // print all of the list elements for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << " "; } return 0; }
main() Function in C++
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Syntax for main() Function in C++
void main() { ............ ............ }
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library. In place of void we can also use int return type of main() function, at that time main() return integer type value. 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace). 3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static. 4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program). 6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed). 7) (since C++20) The main function cannot be a coroutine.
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
/* simple code example by main() function in C++ */ #include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }
For Loop Statement in C++
In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax of For Loop Statement in C++
for (initialization; condition; update) { // body of-loop }
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition. A new range-based for loop was introduced to work with collections such as arrays and vectors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* For Loop Statement in C++ Language */ // C++ program to find the sum of first n natural numbers // positive integers such as 1,2,3,...n are known as natural numbers #include <iostream> using namespace std; int main() { int num, sum; sum = 0; cout << "Enter a positive integer: "; cin >> num; for (int i = 1; i <= num; ++i) { sum += i; } cout << "Sum = " << sum << endl; return 0; }
List Library begin() Function in C++
Return iterator to beginning. Returns an iterator pointing to the first element in the list container. Notice that, unlike member list::front, which returns a reference to the first element, this function returns a bidirectional iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced. begin() function is used to return an iterator pointing to the first element of the list container. It is different from the front() function because the front function returns a reference to the first element of the container but begin() function returns a bidirectional iterator to the first element of the container.
Syntax for List begin() Function in C++
#include <list> iterator begin() noexcept; const_iterator begin() const noexcept;
This function does not accept any parameter. Function returns an iterator to the beginning of the sequence container. If the list object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are bidirectional iterator types (pointing to an element and to a const element, respectively). If list object is constant qualified then method returns constant random access iterator otherwise non constant random access iterator.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* returns a random access iterator which points to the first element of the list by std::list::begin() function code example */ // CPP program to illustrate implementation of end() function #include <iostream> #include <list> using namespace std; int main() { // declaration of list container list<int> mylist{ 1, 2, 3, 4, 5 }; // using end() to print list for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; return 0; }
List in C++ Language
List is a popularly used sequence container. Container is an object that holds data of same type. List container is implemented as doubly linked-list, hence it provides bidirectional sequential access to it's data. List doesn't provide fast random access, it only supports sequential access in both directions. List allows insertion and deletion operation anywhere within a sequence in constant time. Elements of list can be scattered in different chunks of memory. Container stores necessary information to allow sequential access to it's data. Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by internal allocator. Zero sized lists are also valid. In that case list.begin() and list.end() points to same location. But behavior of calling front() or back() is undefined. To define the std::list, we have to import the <list> header file.
Definition Syntax for Lists in C++
template < class Type, class Alloc =allocator<T> > class list;
T
Defines the type of element contained. You can substitute T by any data type, even user-defined types.
Alloc
Defines the type of the allocator object. This uses the allocator class template by default. It's value-dependent and uses a simple memory allocation model. • List is a contiguous container while vector is a non-contiguous container i.e list stores the elements on a contiguous memory and vector stores on a non-contiguous memory. • Insertion and deletion in the middle of the vector is very costly as it takes lot of time in shifting all the elements. Linklist overcome this problem and it is implemented using list container. • List supports a bidirectional and provides an efficient way for insertion and deletion operations. • Traversal is slow in list as list elements are accessed sequentially while vector supports a random access. Following member types can be used as parameters or return type by member functions: • value_type T (First parameter of the template) • allocator_type Alloc (Second parameter of the template) • reference value_type& • const_reference const value_type& • pointer value_type* • const_pointer const value_type* • iterator a random access iterator to value_type • const_iterator a random access iterator to const value_type • reverse_iterator std::reverse_iterator <iterator> • const_reverse_iterator std::reverse_iterator <const_iterator> • size_type size_t • difference_type ptrdiff_t C++ List Member Functions • insert(): It inserts the new element before the position pointed by the iterator. • push_back(): It adds a new element at the end of the vector. • push_front(): It adds a new element to the front. • pop_back(): It deletes the last element. • pop_front(): It deletes the first element. • empty(): It checks whether the list is empty or not. • size(): It finds the number of elements present in the list. • max_size(): It finds the maximum size of the list. • front(): It returns the first element of the list. • back(): It returns the last element of the list. • swap(): It swaps two list when the type of both the list are same. • reverse(): It reverses the elements of the list. • sort(): It sorts the elements of the list in an increasing order. • merge(): It merges the two sorted list. • splice(): It inserts a new list into the invoking list. • unique(): It removes all the duplicate elements from the list. • resize(): It changes the size of the list container. • assign(): It assigns a new element to the list container. • emplace(): It inserts a new element at a specified position. • emplace_back(): It inserts a new element at the end of the vector. • emplace_front(): It inserts a new element at the beginning of the list. Non-member overloaded functions operator== Tests whether two lists are equal or not. 2 operator!= Tests whether two lists are equal or not. 3 operator< Tests whether first list is less than other or not. 4 operator<= Tests whether first list is less than or equal to other or not. 5 operator> Tests whether first list is greater than other or not. 6 operator>= Tests whether first list is greater than or equal to other or not. 7 swap Exchanges the contents of two list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* using lists in C++ language simple code example */ #include <iostream> #include <list> using namespace std; int main(void) { list<int> l; list<int> l1 = { 10, 20, 30 }; list<int> l2(l1.begin(), l1.end()); list<int> l3(move(l1)); cout << "Size of list l: " << l.size() << endl; cout << "List l2 contents: " << endl; for (auto it = l2.begin(); it != l2.end(); ++it) cout << *it << endl; cout << "List l3 contents: " << endl; for (auto it = l3.begin(); it != l3.end(); ++it) cout << *it << endl; return 0; }
#include Directive in C++
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
Namespaces in C++ Language
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code. A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name { // code declarations }
To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows:
name::code; // code could be variable or function.
Using Directive
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files. So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one:
namespace namespace_name { // code declarations }
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another name space as follows:
namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } }
• Namespace is a feature added in C++ and not present in C. • A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it. • Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope. • Namespace declarations appear only at global scope. • Namespace declarations can be nested within another namespace. • Namespace declarations don't have access specifiers. (Public or private) • No need to give semicolon after the closing brace of definition of namespace. • We can split the definition of namespace over several units.
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
/* namespaces in C++ language */ // A C++ code to demonstrate that we can define // methods outside namespace. #include <iostream> using namespace std; // Creating a namespace namespace ns { void display(); class happy { public: void display(); }; } // Defining methods of namespace void ns::happy::display() { cout << "ns::happy::display()\n"; } void ns::display() { cout << "ns::display()\n"; } // Driver code int main() { ns::happy obj; ns::display(); obj.display(); return 0; }
List Library rbegin() Function in C++
Return reverse iterator to reverse beginning. Returns a reverse iterator pointing to the last element in the container (i.e., its reverse beginning). list::rbegin() is an inbuilt function in C++ STL which is declared in header file. rbegin() is a reverse begin function. rebegin() returns a reverse iterator which is pointing to the last element of the list. Reverse iterator is an iterator which moves in reverse direction, starting from the end and will move towards the start. However back() also returns the last element but unlike the simple iterator this bidirectional iterator moves in backward direction. Reverse iterators iterate backwards: increasing them moves them towards the beginning of the container. rbegin points to the element right before the one that would be pointed to by member end. Notice that unlike member list::back, which returns a reference to this same element, this function returns a reverse bidirectional iterator.
Syntax for List rbegin() Function in C++
#include <list> reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept;
This function does not accept any parameter. Function returns a reverse iterator to the reverse beginning of the sequence container. If the list object is const-qualified, the function returns a const_reverse_iterator. Otherwise, it returns a reverse_iterator. Member types reverse_iterator and const_reverse_iterator are reverse bidirectional iterator types (pointing to an element and to a const element, respectively). See list member types.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
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
/* The C++ list::rbegin function returns the reverse iterator pointing to the last element of the list. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the list container. Similarly, decreasing a reverse iterator results into moving to the end of the list container. Please note that, Unlike the list::back function, which returns a direct reference to the last element, it returns the reverse iterator pointing to the same element of the list. */ /* Return reverse iterator to reverse beginning by list rbegin() function code example */ #include <iostream> #include <list> using namespace std; int main (){ list<string> MyList{"Alpha","Coding","Skills"}; list<string>::reverse_iterator rit; rit = MyList.rbegin(); cout<<*rit<<" "; rit++; cout<<*rit<<" "; rit++; cout<<*rit<<" "; return 0; }
What is an Array in C++ Language
An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations. By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.
Properties of Array
The array contains the following properties. • Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes. • Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location. • Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
Advantage of C++ Array
• 1) Code Optimization: Less code to the access the data. • 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily. • 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only. • 4) Random Access: We can access any element randomly using the array.
Disadvantage of C++ Array
• 1) Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C++ is not dynamic. • 2) Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.
Declaration of C++ Array
To declare an array in C++, a programmer specifies the type of the elements and the number of elements required by an array as follows
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C++ either one by one or using a single statement as follows
double balance[5] = {850, 3.0, 7.4, 7.0, 88};
The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write
double balance[] = {850, 3.0, 7.4, 7.0, 88};
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array.
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to salary variable.
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
/* arrays in C++ Language */ #include <iostream> using namespace std; int main() { // initialize an array without specifying size double numbers[] = {7, 5, 6, 12, 35, 27}; double sum = 0; double count = 0; double average; cout << "The numbers are: "; // print array elements // use of range-based for loop for (const double &n : numbers) { cout << n << " "; // calculate the sum sum += n; // count the no. of array elements ++count; } // print the sum cout << "\nTheir Sum = " << sum << endl; // find the average average = sum / count; cout << "Their Average = " << average << endl; return 0; }


Topological sorting for directed acyclic graph (dag) is a linear ordering of vertices such that for every directed edge 'uv', vertex 'u' comes before v in the ordering. 'Topological Sorting'