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

List operations on a deque

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 44 45 46 47 48 49 50 51 52 53 54
/* List operations on a deque */ #include <string> #include <deque> #include <algorithm> #include <iostream> using namespace std; void print( deque<string> ); int main() { deque<string> animals; animals.push_back( "A" ); animals.push_back( "B" ); animals.push_front( "C" ); animals.push_front( "D" ); print(animals); animals.pop_front(); animals.pop_back(); print(animals); //list operations on a deque: animals.erase(find( animals.begin(), animals.end(), "E" )); print(animals); animals.insert( animals.begin(), "F" ); print(animals); int sz = animals.size(); animals.resize( 5 ); animals[sz] = "G"; animals[sz+1] = "H"; animals[sz+2] = "I"; print( animals ); animals.erase( animals.begin() + 2 ); print( animals ); //sorting a deque: sort( animals.begin(), animals.end() ); print( animals ); return 0; } void print( deque<string> d ) { typedef deque<string>::const_iterator CI; cout << "The number of items in the deque:" << d.size() << endl; for ( CI iter = d.begin(); iter != d.end(); iter++ ) cout << *iter << " "; cout << endl << endl; }
Deque Library insert() Function in C++
Insert elements. The deque container is extended by inserting new elements before the element at the specified position. This effectively increases the container size by the amount of elements inserted. C++ Deque insert() function inserts new element just before the specified position pos and the size of the container increases by the number of elements are inserted. Insertion of an element can be done either from front or from the back. Double-ended queues are designed to be efficient performing insertions (and removals) from either the end or the beginning of the sequence. Insertions on other positions are usually less efficient than in list or forward_list containers. The parameters determine how many elements are inserted and to which values they are initialized:
Syntax for Deque insert() Function in C++
#include <deque> //single element (1) iterator insert (const_iterator position, const value_type& val); //fill (2) iterator insert (const_iterator position, size_type n, const value_type& val); //range (3) template <class InputIterator> iterator insert (const_iterator position, InputIterator first, InputIterator last); //move (4) iterator insert (const_iterator position, value_type&& val); //initializer list (5) iterator insert (const_iterator position, initializer_list<value_type> il);
position
Position in the container where the new elements are inserted. iterator is a member type, defined as a random access iterator type that points to elements.
val
Value to be copied (or moved) to the inserted elements. Member type value_type is the type of the elements in the container, defined in deque as an alias of its first template parameter (T).
n
Number of elements to insert. Each element is initialized to a copy of val. Member type size_type is an unsigned integral type.
first, last
Iterators specifying a range of elements. Copies of the elements in the range [first,last) are inserted at position (in the same order). Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last. The function template argument InputIterator shall be an input iterator type that points to elements of a type from which value_type objects can be constructed.
il
An initializer_list object. Copies of these elements are inserted at position (in the same order). These objects are automatically constructed from initializer list declarators. Member type value_type is the type of the elements in the container, defined in deque as an alias of its first template parameter (T). Function returns an iterator that points to the first of the newly inserted elements. Member type iterator is a random access iterator type that points to elements. 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
Linear on the number of elements inserted (copy/move construction). Plus, depending on the particular library implemention, up to an additional linear in the number of elements between position and one of the ends of the deque.
Iterator validity
If the insertion happens at the beginning or the end of the sequence, all iterators related to this container are invalidated, but pointers and references remain valid, referring to the same elements they were referring to before the call. If the insertion happens anywhere else in the deque, all iterators, pointers and references related to this container are invalidated.
Data races
The container is modified. If the insertion happens at the beginning or the end of the sequence, no contained elements are accessed (although see iterator validity above). If it happens anywhere else, it is not safe to concurrently access elements.
Exception safety
If the operation inserts a single element at the begin or the end, there are no changes in the container in case of exception (strong guarantee). Otherwise, the container is guaranteed to end in a valid state (basic guarantee). If allocator_traits::construct is not supported with the appropriate arguments for the element constructions, or if an invalid position or range is specified, 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 30 31 32 33 34 35 36 37 38 39 40 41
/* insert new elements before the element at the specified position by deque::insert function code example. */ #include <iostream> #include <deque> using namespace std; int main (){ deque<int> deque1 = {10, 20, 30}; deque<int> deque2 = {10, 20, 30}; deque<int> deque3 = {10, 20, 30}; deque<int> deque4 = {100, 200, 300}; deque<int>::iterator it; //single element version it = deque1.begin(); deque1.insert(it + 2, 55); //fill version - fill 3 new elements at specified location it = deque2.begin(); deque2.insert(it + 2, 3, 55); //range version it = deque3.begin(); deque3.insert(it+2, deque4.begin(), deque4.end()); cout<<"deque1 contains: "; for(it = deque1.begin(); it != deque1.end(); ++it) cout<<*it<<" "; cout<<"\ndeque2 contains: "; for(it = deque2.begin(); it != deque2.end(); ++it) cout<<*it<<" "; cout<<"\ndeque3 contains: "; for(it = deque3.begin(); it != deque3.end(); ++it) cout<<*it<<" "; 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; }
Deque Library pop_back() Function in C++
Delete last element. Removes the last element in the deque container, effectively reducing the container size by one. pop_back() function is used to pop or remove elements from a deque from the back. The value is removed from the deque from the end, and the container size is decreased by 1. This destroys the removed element.
Syntax for Deque pop_back() Function in C++
#include <deque> void pop_back();
This function does not accept any parameter. This function does not return any value.
Complexity
Constant
Iterator validity
The end iterator and any iterator, pointer and reference referring to the removed element are invalidated. Iterators, pointers and references referring to other elements that have not been removed are guaranteed to keep referring to the same elements they were referring to before the call.
Data races
The container is modified. The last element is modified. Concurrently accessing or modifying other elements is safe (although see iterator validity above).
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, the behavior is undefined.
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++ deque::pop_back function is used to delete the last element of the deque. Every deletion of element results into reducing the container size by one unless the deque is empty. */ /* Delete last element by deque pop_back() function code example */ #include <iostream> #include <deque> using namespace std; int main (){ deque<int> MyDeque{100, 200, 300, 400, 500, 600}; deque<int>::iterator it; //deletes last element of the deque MyDeque.pop_back(); //deletes next last element of the deque MyDeque.pop_back(); cout<<"The deque contains:"; for(it = MyDeque.begin(); it != MyDeque.end(); ++it) cout<<" "<<*it; return 0; }
Deque Library resize() Function in C++
Change size. Resizes the container so that it contains n elements. C++ Deque resize() function changes the size of the deque container to the size given in the argument. If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them). If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized. Notice that this function changes the actual content of the container by inserting or erasing elements from it.
Syntax for Deque resize() Function in C++
#include <deque> void resize (size_type n); void resize (size_type n, const value_type& val);
n
New container size, expressed in number of elements. Member type size_type is an unsigned integral type.
val
Object whose content is copied to the added elements in case that n is greater than the current container size. If not specified, the default constructor is used instead. Member type value_type is the type of the elements in the container, defined in deque as an alias of the first template parameter (T). This function does not return any value. In case of growth, 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
Linear on the number of elements inserted/erased (constructions/destructions).
Iterator validity
In case the container shrinks, all iterators, pointers and references to elements that have not been removed remain valid after the resize and refer to the same elements they were referring to before the call. If the container expands, all iterators are invalidated, but existing pointers and references remain valid, referring to the same elements they were referring to before.
Data races
The container is modified. Removed elements are modified (see iterator validity above).
Exception safety
If n is less than or equal to the size of the container, the function never throws exceptions (no-throw guarantee). Otherwise, if an exception is thrown, the container is left with a valid state (basic guarantee): Constructing elements or allocating storage may 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 36
/* The C++ function std::deque::resize() changes the size of deque. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of deque. If val is specified then new elements are initialed with val. */ /* change the size of the deque container to the size given in the argument by Deque resize() function code example. */ #include <bits/stdc++.h> using namespace std; int main() { deque<int> dq = { 10, 20, 30, 40, 50 }; cout << "Size before resize " << dq.size() << "\n"; // Prints the deque elements cout << "The contents of deque :"; for (auto it = dq.begin(); it != dq.end(); ++it) cout << *it << " "; cout << endl; // resize to 7 dq.resize(7); // // Prints the deque elements after resize() cout << "Size after resize " << dq.size() << "\n"; cout << "The contents of deque :"; for (auto it = dq.begin(); it != dq.end(); ++it) cout << *it << " "; 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; }
Deque Library begin() Function in C++
Return iterator to beginning. Returns an iterator pointing to the first element in the deque container. Notice that, unlike member deque::front, which returns a reference to the first element, this function returns a random access iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced. deque::begin() is an inbuilt function in C++ STL which is declared in header file. deque::begin() returns an iterator which is referencing to the first element of the deque container associated with the function. Both begin() and end() are used to iterate through the deque container.
Syntax for Deque begin() Function in C++
#include <deque> 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 deque object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are random access iterator types (pointing to an element and to a const element, respectively).
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
/* returns an iterator pointing to the first element in the deque container by std::deque::begin function code example. */ // CPP program to illustrate implementation of end() function #include <deque> #include <iostream> using namespace std; int main() { // declaration of deque container deque<int> mydeque{ 1, 2, 3, 4, 5 }; // using end() to print deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; 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; }
Deque Library erase() Function in C++
Erase elements. Removes from the deque container either a single element (position) or a range of elements ([first,last)). C++ Deque erase() function removes the element from the specified position or range and this effectively reduces the size of the deque by the number of elements removed. This effectively reduces the container size by the number of elements removed, which are destroyed. Double-ended queues are designed to be efficient removing (and inserting) elements at either the end or the beginning of the sequence. Removals on other positions are usually less efficient than in list or forward_list containers.
Syntax for Deque erase() Function in C++
#include <deque> iterator erase (const_iterator position ); iterator erase (const_iterator first, const_iterator last );
position
Iterator pointing to a single element to be removed from the deque. Member types iterator and const_iterator are random access iterator types that point to elements.
first, last
Iterators specifying a range within the deque] to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last. Member types iterator and const_iterator are random access iterator types that point to elements. Function returns an iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence. Member type iterator is a random access iterator type that points to elements.
Complexity
Linear on the number of elements erased (destructions). Plus, depending on the particular library implemention, up to an additional linear time on the number of elements between position and one of the ends of the deque.
Iterator validity
If the erasure operation includes the last element in the sequence, the end iterator and the iterators, pointers and references referring to the erased elements are invalidated. If the erasure includes the first element but not the last, only those referring to the erased elements are invalidated. If it happens anywhere else in the deque, all iterators, pointers and references related to the container are invalidated.
Data races
The container is modified. If the erasure happens at the beginning or the end of the sequence, only the erased elements are modified (although see iterator validity above). If it happens anywhere else, it is not safe to access or modify elements.
Exception safety
If the removed elements include the first or the last element in the container, no exceptions are thrown (no-throw guarantee). Otherwise, the container is guaranteed to end in a valid state (basic guarantee): Copying or moving elements while relocating them may throw. Invalid ranges produce 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 30
/* deque erase() function is used to remove the element from the container at specified position and in a range. This function reduces the size of the deque container by the number of elements removed. Deque containers are efficient in removing or inserting the elements at the beginning or at the end of the deque container. */ /* remove elements from a container from the specified position or range by deque erase() function code example. */ #include <deque> #include <iostream> using namespace std; int main() { deque<int> mydeque{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; deque<int>::iterator i; i = mydeque.begin(); while (i != mydeque.end()) { if (*i % 2 == 0) /* Not a good idea to erase inside loop, if you delete last element, mydeque.end() cannot be found resulting in infinite loop */ mydeque.erase(i); i++; } // Printing the deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; 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; }
Deque Library push_front() Function in C++
Insert element at beginning. Inserts a new element at the beginning of the deque container, right before its current first element. The content of val is copied (or moved) to the inserted element. This effectively increases the container size by one. deque::push_front() is an inbuilt function in C++ STL which is declared in header file. deque::push_front() is used to push/insert an element at the front or at the beginning of the deque container making the pushed/inserted element as the first element of the deque. This function accepts one argument, that is, the element which is to be pushed/inserted at the beginning.
Syntax for Deque push_front() Function in C++
#include <deque> void push_front (const value_type& val); void push_front (value_type&& val);
val
Value to be copied (or moved) to the inserted element. Member type value_type is the type of the elements in the container, defined in deque as an alias of its first template parameter (T). 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
All iterators related to this container are invalidated. Pointers and references to elements in the container remain valid, referring to the same elements they were referring to before the call.
Data races
The container is modified. No existing elements are accessed (although see iterator validity above).
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
/* push_front() function is used to push elements into a deque from the front. The new value is inserted into the deque at the beginning, before the current first element and the container size is increased by 1. */ // CPP program code example to illustrate application of push_front() function #include <deque> #include <iostream> using namespace std; int main() { int count = 0; deque<int> mydeque; mydeque.push_front(1); mydeque.push_front(2); mydeque.push_front(3); mydeque.push_front(4); mydeque.push_front(5); mydeque.push_front(6); while (!mydeque.empty()) { count++; mydeque.pop_front(); } cout << count; return 0; }
Deque Library pop_front() Function in C++
Delete first element. Removes the first element in the deque container, effectively reducing its size by one. This destroys the removed element. The C++ deque::pop_front function is used to delete the first element of the deque. Every deletion of element results into reducing the container size by one unless the deque is empty. Removes the first element of the container. If there are no elements in the container, the behavior is undefined. Iterators and references to the erased element are invalidated. If the element is the last element in the container, the past-the-end iterator is also invalidated. Other references and iterators are not affected.
Syntax for Deque pop_front() Function in C++
#include <deque> void pop_front();
This function does not accept any parameter. This function does not return any value.
Complexity
Constant
Iterator validity
The iterators, pointers and references referring to the removed element are invalidated. Iterators, pointers and references referring to other elements that have not been removed are guaranteed to keep referring to the same elements they were referring to before the call.
Data races
The container is modified. The first element is modified. Concurrently accessing or modifying other elements is safe (although see iterator validity above).
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, the behavior is undefined.
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
/* deque pop_front() function is used to pop or remove elements from a deque from the front. The value is removed from the deque from the beginning, and the container size is decreased by 1. */ /* Delete first element by std::deque::pop_front function code example */ #include <iostream> #include <deque> using namespace std; int main (){ deque<int> MyDeque{100, 200, 300, 400, 500, 600}; deque<int>::iterator it; //deletes first element of the deque MyDeque.pop_front(); //deletes next first element of the deque MyDeque.pop_front(); cout<<"The deque contains:"; for(it = MyDeque.begin(); it != MyDeque.end(); ++it) cout<<" "<<*it; return 0; }
Deque Library end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the deque container. The past-the-end element is the theoretical element that would follow the last element in the deque 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 deque::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as deque::begin. deque::end() is an inbuilt function in C++ STL which is declared in<deque> header file. deque::end() returns an iterator which is referencing next to the last element of the deque container associated with the function. Both begin() and end() are used to iterate through the deque container.
Syntax for Deque end() Function in C++
#include <deque> 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 deque object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are random access iterator types (pointing to an element and to a const element, respectively).
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
/* returns a random access iterator which points to the last element of the deque by std::deque::end() function code example. */ // CPP program to illustrate implementation of end() function #include <deque> #include <iostream> using namespace std; int main() { // declaration of deque container deque<int> mydeque{ 1, 2, 3, 4, 5 }; // using end() to print deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; return 0; }
Deque Library size() Function in C++
Return size. Returns the number of elements in the deque container. deque::size() is an inbuilt function in C++ STL which is declared in header file. deque::size() returns the size of the deque container associated with the function. If the container has no elements then the function returns 0. size() function is used to return the size of the deque container or the number of elements in the deque container. This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <deque> header file. The function either returns a number demonstrating the total elements the deque holds at that instance.
Syntax for Deque size() Function in C++
#include <deque> size_type size() const noexcept;
This function does not accept any parameter. Function returns the number of elements in the container. Member type size_type is an unsigned integral type.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions.
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
/* C++ Deque size() function determines the number of elements present in the deque container. */ // CPP program code example to demonstrate implementation of Deque size() function #include <deque> #include <iostream> using namespace std; // Driver Code int main() { int sum = 0; deque<int> mydeque; mydeque.push_back(1); mydeque.push_back(8); mydeque.push_back(3); mydeque.push_back(6); mydeque.push_back(2); // deque becomes 1, 8, 3, 6, 2 cout << mydeque.size(); return 0; }
Deque Library push_back() Function in C++
Add element at the end. Adds a new element at the end of the deque 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. push_back() function is used to push elements into a deque from the back. The new value is inserted into the deque at the end, before the current last element and the container size is increased by 1.
Syntax for Deque push_back() Function in C++
#include <deque> 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 deque as an alias of its first template parameter (T). 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
All iterators related to this container are invalidated. Pointers and references to elements in the container remain valid, referring to the same elements they were referring to before the call.
Data races
The container is modified. No existing elements are accessed (although see iterator validity above).
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
/* C++ Deque push_back() function adds a new element at the end of the deque container and the size of the container is increased by one. */ // C++ code example to demonstrate the working of deque push_back( ) function #include<iostream.h> #include<deque.h> Using namespace std; int main ( ){ // initializing the deque Deque<int> deque = { 71, 75, 73, 76, 77 }; // print the deque cout<< " Deque: "; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< *x << " "; // defining the push_backt( ) function deque.push_back(78); // printing new deque after inserting new element for( x = deque.begin( ); x != deque.end( ); ++x) cout<< " " << *x; return 0; }
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; }
Deque in C++ Language
deque (usually pronounced like "deck") is an irregular acronym of double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be expanded or contracted on both ends (either its front or its back). Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any case, they allow for the individual elements to be accessed directly through random access iterators, with storage handled automatically by expanding and contracting the container as needed. Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of elements also at the beginning of the sequence, and not only at its end. But, unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations: accessing elements in a deque by offsetting a pointer to another element causes undefined behavior. Both vectors and deques provide a very similar interface and can be used for similar purposes, but internally both work in quite different ways: While vectors use a single array that needs to be occasionally reallocated for growth, the elements of a deque can be scattered in different chunks of storage, with the container keeping the necessary information internally to provide direct access to any of its elements in constant time and with a uniform sequential interface (through iterators). Therefore, deques are a little more complex internally than vectors, but this allows them to grow more efficiently under certain circumstances, especially with very long sequences, where reallocations become more expensive. For operations that involve frequent insertion or removals of elements at positions other than the beginning or the end, deques perform worse and have less consistent iterators and references than lists and forward lists.
Syntax for Deque in C++
#include <deque> template < class T, class Alloc = allocator<T> > class deque;
T
Type of the elements. Aliased as member type deque::value_type.
Alloc
Type of the allocator object used to define the storage allocation model. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent. Aliased as member type deque::allocator_type. Sequence: Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by their position in this sequence. Dynamic array: Generally implemented as a dynamic array, it allows direct access to any element in the sequence and provides relatively fast addition/removal of elements at the beginning or the end of the sequence. Allocator-aware: The container uses an allocator object to dynamically handle its storage needs.
Initialize a Deque in C++
// method 1: initializer list deque<int> deque1 = {1, 2, 3, 4, 5}; // method 2: uniform initialization deque<int> deque2 {1, 2, 3, 4, 5};
Deque Member Types
• value_type T (First template parameter) • allocator_type Alloc (Second template parameter), default: allocator<value_type> • reference value_type& • const_reference const value_type& • pointer Alloc::pointer, default: value_type* • const_pointer Alloc::const_pointer, default: value_type* • iterator a random access iterator to value_type • const_iterator a random access iterator to const value_type • reverse_iterator reverse_iterator <iterator> • const_reverse_iterator reverse_iterator <const_iterator> • difference_type ptrdiff_t • size_type size_t
C++ Deque Functions
• deque() Construct a deque object. • ~deque() Destroys container by deallocating container memory. • operator=() Assign content to a deque. • empty() Checks whether the deque is empty or not. • size() Returns the length of the deque in terms of bytes. • max_size() Returns the maximum length of the deque. • resize() Changes the size of the deque by specified number of elements. • shrink_to_fit() Reduces the capacity of the deque equal to fit its size. • at() Access an element of the deque. • operator[]() Access an element of the deque. • front() Access first element of the deque. • back() Access last element of the deque. • begin() Returns iterator pointing to the first element of the deque. • end() Returns iterator pointing to the past-the-last element of the deque. • rbegin() Returns reverse iterator to the last element of the deque. • rend() Returns reverse iterator to the element preceding the first element of the deque. • cbegin() Returns const_iterator pointing to the first element of the deque. • cend() Returns const_iterator pointing to the past-the-last element of the deque. • crbegin() Returns const_reverse_iterator to the last element of the deque. • crend() Returns const_reverse_iterator to the element preceding the first element of the deque. • assign() Assign deque content. • clear() Clears all elements of the deque. • pop_front() Deletes first element of the deque. • push_front() Adds a new element at the beginning of the deque. • pop_back() Deletes last element of the deque. • push_back() Adds a new element at the end of the deque. • insert() Insert elements in the deque. • erase() Deletes either a single element or range of elements from a deque. • emplace() Constructs and inserts a new element at specified position in the deque • emplace_front() Constructs and inserts a new element at the beginning of the deque. • emplace_back() Constructs and inserts a new element at the end of the deque. • swap() Exchanges elements between two deques. • get_allocator() Return a copy of allocator object associated with the deque. • operator == Checks whether two deques are equal or not. • operator != Checks whether two deques are unequal or not. • operator < Checks whether the first deque is less than the other or not. • operator > Checks whether the first deque is greater than the other or not. • operator <= Checks whether the first deque is less than or equal to the other or not. • operator >= Checks whether the first deque is greater than or equal to the other or not. • swap() Exchanges elements between two deques.
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
/* In C++, the STL deque is a sequential container that provides the functionality of a double-ended queue data structure. */ #include <iostream> #include <deque> using namespace std; // function prototype void display_deque(deque<int>); int main() { // uniform initialization deque<int> deque1 {1, 2, 3, 4, 5}; cout << "deque1 = "; // display elements of deque1 for (int num : deque1) { cout << num << ", "; } return 0; }
Deque Library operator[] Index in C++
Access element. Returns a reference to the element at position n in the deque container. This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of deque, while this operator causes undefined behavior. A similar member function, deque::at, has the same behavior as this operator function, except that deque::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception.
Syntax for Deque operator[] Index in C++
#include <deque> reference operator[] (size_type n); const_reference operator[] (size_type n) const;
n
Position of an element in the container. Notice that the first element has a position of 0 (not 1). Member type size_type is an unsigned integral type. Function returns the element at the specified position in the container. Member types reference and const_reference are the reference types to the elements of the container (see deque 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). Element n is potentially accessed or modified. Concurrently accessing or modifying other elements is safe.
Exception safety
If the container size is greater than n, the function never throws exceptions (no-throw guarantee). Otherwise, the behavior is undefined (which may include throwing).
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
/* C++ Deque operator[] function is used to access the element at specified position pos. If position pos is greater than the size of container then it returns a value 0. */ /* Access element from Deque by operator[] code example */ // deque::operator[] example: reversing order #include <iostream> #include <deque> int main () { std::deque<int> mydeque (10); // 10 zero-initialized elements std::deque<int>::size_type sz = mydeque.size(); // assign some values: for (unsigned i=0; i<sz; i++) mydeque[i]=i; // reverse order of elements using operator[]: for (unsigned i=0; i<sz/2; i++) { int temp; temp = mydeque[sz-1-i]; mydeque[sz-1-i]=mydeque[i]; mydeque[i]=temp; } // print content: std::cout << "mydeque contains:"; for (unsigned i=0; i<sz; i++) std::cout << ' ' << mydeque[i]; std::cout << '\n'; return 0; }
Algorithm Library find() Function in C++
C++ find() function is part of the standard library function which tries to find the first occurrence of the specified range of element where the range starts with first range to last range and that iterator encounters the first element, compares for the value which must be equal after all possible comparisons and if no element is found it returns the last element. For making all the comparisons it makes use of the operator = for comparison. If find() function performs any unnecessary action it throws exceptions that are not required by the programmer. Find value in range. Returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last. The function uses operator== to compare the individual elements to val.
Syntax for find() Function in C++
template <class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val);
first
Input iterator to the initial position.
last
Input iterator to the final position. Input iterators to the initial and final positions in a sequence. The range searched is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
val
Value to compare the elements. Value to search for in the range. T shall be a type supporting comparisons with the elements pointed by InputIterator using operator== (with the elements as left-hand side operands, and val as right-hand side). Function returns an iterator to the first element in the range that compares equal to val. If no elements match, the function returns last. If element found it returns an iterator pointing to the first occurrence of the element otherwise returns last. Throws exception if either element comparison or an operation on an iterator throws exception. Please note that invalid parameters cause undefined behavior. Any find() function defined should have a proper standard library for inclusion otherwise it will throw an unwanted exception saying that this member or method is not present with the designated standard library for the function which means incompatibility of function with the standard library. Advantages of C++ algorithm library find() function: • find() function as part of the standard library can be used by the programmers for searching elements at the time of comparison with the first and last element within a specified range. • The iterator pointing to the first or the last element can enhance or manipulate the entire traversal process as all the elements present are with the index were retrieving the value is important for comparisons and other operations. • It enhances the reusability of the code base as it not important to design and define a function again and again wherever required we can call the find function and the task becomes simplified as it will be already present within the standard library. • Testing of individual functions becomes easy as the scope for re-writing function becomes simplified. • The division of the program makes the view of the codebase clear and understandable by the programmers to write a new and enhanced form of code.
Complexity
Up to linear in the distance between first and last: Compares elements until a match is found.
Data races
Some (or all) of the objects in the range [first,last) are accessed (once at most).
Exceptions
Throws if either an element comparison or an operation on an iterator throws. Note that invalid arguments cause 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
/* algorithm library find() function in C++ language */ #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(void) { int val = 5; vector<int> v = {1, 2, 3, 4, 5}; auto result = find(v.begin(), v.end(), val); if (result != end(v)) cout << "Vector contains element " << val << endl; val = 15; result = find(v.begin(), v.end(), val); if (result == end(v)) cout << "Vector doesn't contain element " << val << endl; return 0; }
Algorithm Library sort() Function in C++
Sort elements in range. Sorts the elements in the range [first,last) into ascending order. The elements are compared using operator< for the first version, and comp for the second. Equivalent elements are not guaranteed to keep their original relative order (see stable_sort). C++ Algorithm sort() function is used to sort the elements in the range [first, last) into ascending order. The elements are compared using operator < for the first version, and comp for the second version. std::sort() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, and (by default) sorts the iterable in ascending order. The function can also be used for custom sorting by passing in a comparator function that returns a boolean.
Syntax for sort() Function in C++
#include <algorithm> default (1) template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last); custom (2) template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
first, last
Random-access iterators to the initial and final positions of the sequence to be sorted. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. RandomAccessIterator shall point to a type for which swap is properly defined and which is both move-constructible and move-assignable.
comp
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object. This function does not return any value.
Complexity
On average, linearithmic in the distance between first and last: Performs approximately N*log2(N) (where N is this distance) comparisons of elements, and up to that many element swaps (or moves).
Data races
The objects in the range [first,last) are modified.
Exceptions
Throws if any of the element comparisons, the element swaps (or moves) or the operations on iterators throws. Note that invalid arguments cause 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 30 31 32 33 34 35 36 37 38 39 40 41
/* sort a number of elements or a list of elements within first to last elements, in an ascending or a descending order by sort() function code example */ #include <iostream> #include <vector> #include <algorithm> #include <functional> using namespace std; void print(const vector <std::string>& v) { vector <string>::const_iterator i; for(i = v.begin(); i != v.end(); i++) { cout << *i << " "; } cout << endl; } int main() { vector <string> v; // Push functional programming languages v.push_back("Lisp"); v.push_back("C#"); v.push_back("Java"); v.push_back("Python"); v.push_back("C++"); v.push_back("Pascal"); v.push_back("Sql"); // sort without predicate sort(v.begin(), v.end()); cout << "Sorted list of functional programming languages - " << endl; print(v); // sort with predicate sort(v.begin(), v.end(), std::greater<std::string>()); cout << "Reverse Sorted list of functional programming languages - " << endl; print(v); }


To convert decimal number to octal number in C++ programming, you have to ask to the user to enter the decimal number to convert it into octal number to display the equivalent
A simple C++ Calculator which have different functions for different operations. menu base selection screen using switch statement. Ever operation should have its own function. Code