C++ Programming Code Examples
C++ > Code Snippets Code Examples
Demonstrate a deque.
/* Demonstrate a deque. */
#include <iostream>
#include <deque>
#include <cstring>
using namespace std;
int main()
{
deque<char> dequeObject1;
char str[] = "Using a deque.";
int i;
for(i = 0; str[i]; i++) {
dequeObject1.push_front(str[i]);
dequeObject1.push_back(str[i]);
}
cout << "Original dequeObject1:\n";
for(i = 0; i <dequeObject1.size(); i++)
cout << dequeObject1[i];
cout << "\n\n";
for(i = 0; i <strlen(str); i++)
dequeObject1.pop_front();
cout << "dequeObject1 after popping front:\n";
for(i = 0; i <dequeObject1.size(); i++)
cout << dequeObject1[i];
cout << "\n\n";
deque<char> dequeObject2(dequeObject1);
cout << "dequeObject2 original contents:\n";
for(i = 0; i <dequeObject2.size(); i++)
cout << dequeObject2[i];
cout << "\n\n";
for(i = 0; i <dequeObject2.size(); i++)
dequeObject2[i] = dequeObject2[i]+1;
cout << "dequeObject2 transposed contents:\n";
for(i = 0; i <dequeObject2.size(); i++)
cout << dequeObject2[i];
cout << "\n\n";
deque<char>::iterator p = dequeObject1.begin();
while(p != dequeObject1.end()) {
if(*p == 'a') break;
p++;
}
dequeObject1.insert(p, dequeObject2.begin(), dequeObject2.end());
cout << "dequeObject1 after insertion:\n";
for(i = 0; i <dequeObject1.size(); i++)
cout << dequeObject1[i];
cout << "\n\n";
return 0;
}
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.
Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.
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.
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.
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. • 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.
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. This function does not accept any parameter.
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. This function does not return any value.
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. This function does not accept any parameter. This function does not return any value.
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.
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
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.
#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.
Get string length. Returns the length of the C string str. C++ strlen() is an inbuilt function that is used to calculate the length of the string. It is a beneficial method to find the length of the string. The strlen() function is defined under the string.h header file. The strlen() takes a null-terminated byte string str as its argument and returns its length. The length does not include a null character. If there is no null character in the string, the behavior of the function is undefined.
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
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.
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.
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. Function returns the element at the specified position in the container.
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: