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++ > Visual C++ 5.0 Standard C++ Library Code Examples

Vector back - Returns a const reference to the last element

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
Vector back - Returns a const reference to the last element back Header <vector> const_reference back()const Returns a const reference to the last element. It is identical to *(end() - 1). If the container is empty, the result is undefined. reference back() Returns a reference to the last element. It is identical to *(end() - 1). If the container is empty, the result is undefined. Sample #include <vector> #include <iostream> int main() { //default constructor std::vector<int> c1 ; //create vector with 10 copies of 4 std::vector<int> c2(10, 4) ; //copy constructor std::vector<int> c3(c2) ; int ai[] = {0, 1, 2, 3, 4, 5} ; int i ; //range copy constructor std::vector<int> c4(ai, ai+5) ; std::vector<int> c5 ; //push_back for(i = 0; i < 5; i++) c5.push_back(ai[i]) ; //get_allocator std::vector<int>::allocator_type a1 = c4.get_allocator() ; //begin, end std::cout << "c4 (using begin, end) = " ; std::vector<int>::iterator Iter ; for(Iter = c4.begin(); Iter != c4.end(); Iter++) std::cout << *Iter << ", " ; std::cout << std::endl ; //rbegin, rend std::cout << "c4 (using rbegin, rend) = " ; std::vector<int>::reverse_iterator RevIter ; for(RevIter = c4.rbegin(); RevIter != c4.rend(); RevIter++) std::cout << *RevIter << ", " ; std::cout << std::endl ; //assign c2.assign(ai, ai+4) ; c1.assign(10, 4) ; //at std::cout << "third element in c1 = " << c1.at(3) << std::endl ; //operator[] std::cout << "c4[3] = " << c4[3] << std::endl ; //back std::cout << "last element in c2 = " << c2.back() << std::endl ; //front std::cout << "first element in c2 = " << c2.front() << std::endl ; //size std::cout << "number of elements in c2 = " << c2.size() << std::endl ; //max_size std::cout << "max number of elements c2 can hold using current allocator = " << c2.max_size() << std::endl ; //erase c3.erase(c3.begin(), c3.begin() + 4) ; //clear c2.clear() ; //empty if (c2.empty() == true) std::cout << "c2 is now empty" << std::endl ; //resize c2.resize(10, 30) ; std::cout << "number of elements in c2 = " << c2.size() << std::endl ; std::cout << "last element in c2 = " << c2.back() << std::endl ; std::cout << "first element in c2 = " << c2.front() << std::endl ; //reserve, capacity c2.reserve(70) ; std::cout << "current capacity of c2 = " << c2.capacity() << std::endl ; //pop_back c2.pop_back() ; std::cout << "last element in c2 = " << c2.back() << std::endl ; //swap c3.swap(c2) ; std::cout << "number of elements in c3 = " << c3.size() << std::endl ; std::cout << "last element in c3 = " << c3.back() << std::endl ; std::cout << "first element in c3 = " << c3.front() << std::endl ; //insert c1.insert(c1.begin(), 20) ; c1.insert(c1.begin()+1, 4, 10) ; c1.insert(c1.begin()+2, c5.begin(), c5.end()) ; std::cout << "c1 = " ; for(Iter = c1.begin(); Iter != c1.end(); Iter++) std::cout << *Iter << ", " ; std::cout << std::endl ; return 0 ; } Program Output c4 (using begin, end) = 0, 1, 2, 3, 4, c4 (using rbegin, rend) = 4, 3, 2, 1, 0, third element in c1 = 4 c4[3] = 3 last element in c2 = 3 first element in c2 = 0 number of elements in c2 = 4 max number of elements c2 can hold using current allocator = 1073741823 c2 is now empty number of elements in c2 = 10 last element in c2 = 30 first element in c2 = 30 current capacity of c2 = 70 last element in c2 = 30 number of elements in c3 = 9 last element in c3 = 30 first element in c3 = 30 c1 = 20, 10, 0, 1, 2, 3, 4, 10, 10, 10, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
Vector Library push_back() Function in C++
Add element at the end. Adds a new element at the end of the vector, 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, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity. push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1.
Syntax for Vector push_back() Function in C++
#include <vector> 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 vector as an alias of its first template parameter (T). This function does not return any value. If a reallocation happens, the storage 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 (amortized time, reallocation may happen). If a reallocation happens, the reallocation is itself up to linear in the entire size.
Iterator validity
If a reallocation happens, all iterators, pointers and references related to the container are invalidated. Otherwise, only the end iterator is invalidated, and all iterators, pointers and references to elements are guaranteed to keep referring to the same elements they were referring to before the call.
Data races
The container is modified. If a reallocation happens, all contained elements are modified. Otherwise, no existing element is accessed, and concurrently accessing or modifying them is safe.
Exception safety
If no reallocations happen, there are no changes in the container in case of exception (strong guarantee). If a reallocation happens, the strong guarantee is also given if the type of the elements is either copyable or no-throw moveable. Otherwise, the container is guaranteed to end in a valid state (basic guarantee). 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 30 31 32 33 34
/* vector::push_back() is a library function of "vector" header, it is used to insert/add an element at the end of the vector, it accepts an element of the same type and adds the given element at the end of the vector and increases the size of the vector. */ //C++ STL program code example to demonstrate example of vector::push_back() function #include <iostream> #include <vector> using namespace std; int main() { //vector declaration vector<int> v1; //inserting elements and printing size cout << "size of v1: " << v1.size() << endl; v1.push_back(10); cout << "size of v1: " << v1.size() << endl; v1.push_back(20); v1.push_back(30); v1.push_back(40); v1.push_back(50); cout << "size of v1: " << v1.size() << endl; //printing all elements cout << "elements of vector v1..." << endl; for (int x : v1) cout << x << " "; cout << endl; return 0; }
Vector Library at() Function in C++
Access element. Returns a reference to the element at position n in the vector. The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater than, or equal to, its size). This is in contrast with member operator[], that does not check against bounds.
Syntax for Vector at() Function in C++
#include <vector> reference at (size_type n); const_reference at (size_type n) const;
n
Position of an element in the container. If this is greater than, or equal to, the vector size, an exception of type out_of_range is thrown. 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. If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference. Member types reference and const_reference are the reference types to the elements of the container (see vector 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). The reference returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container. It throws out_of_range if n is out of bounds.
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
/* The C++ function std::vector::at() returns reference to the element present at location n in the vector. */ /* give a reference to an element by vector at() function code example. */ #include <iostream> #include <vector> using namespace std; int main() { vector<int> myvector; myvector.push_back(1); myvector.push_back(2); myvector.push_back(3); myvector.push_back(4); myvector.push_back(5); myvector.push_back(6); myvector.push_back(7); myvector.push_back(8); myvector.push_back(9); // vector becomes 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < myvector.size(); i += 2) { cout << myvector.at(i); cout << " "; } return 0; }
If Else Statement in C++
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,
Syntax for If Statement in C++
if (condition) { // body of if 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.
Syntax for If...Else Statement
if (condition) { // block of code if condition is true } else { // block of code if condition is false }
The if..else statement evaluates the condition inside the parenthesis. If the condition evaluates true, the code inside the body of if is executed, the code inside the body of else is skipped from execution. If the condition evaluates false, the code inside the body of else is executed, the code inside the body of if is skipped from execution. The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.
Syntax for If...Else...Else If Statement in C++
if (condition1) { // code block 1 } else if (condition2){ // code block 2 } else { // code block 3 }
• If condition1 evaluates to true, the code block 1 is executed. • If condition1 evaluates to false, then condition2 is evaluated. • If condition2 is true, the code block 2 is executed. • If condition2 is false, the code block 3 is executed. There can be more than one else if statement but only one if and else statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax for If Else If Ladder in C++
if (condition) statement 1; else if (condition) statement 2; . . else statement;
Working of the if-else-if ladder: 1. Control falls into the if block. 2. The flow jumps to Condition 1. 3. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. 4. The present block is executed. Goto Step 7. 5. The flow jumps to Condition 2. If Condition yields true, goto step 4. If Condition yields false, goto Step 6. 6. The flow jumps to Condition 3. If Condition yields true, goto step 4. If Condition yields false, execute else block. Goto Step 7. 7. Exits the if-else-if ladder. • The if else ladder statement in C++ programming language is used to check set of conditions in sequence. • This is useful when we want to selectively executes one code block(out of many) based on certain conditions. • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions. • A condition expression is tested only when all previous if conditions in if-else ladder is false. • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* If Else Statement in C++ Language */ #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } else { // if condition is false then print the following cout << "a is not less than 20;" << endl; } cout << "value of a is : " << a << endl; return 0; }
Vector Library clear() Function in C++
The C++ vector has many member functions. Two of them are clear() and erase(). clear() "removes" all the elements of the vector. erase() "removes" a single element or a range of elements. vector::clear() is a library function of "vector" header, it is used to remove/clear all elements of the vector, it makes the 0 sized vector after removing all elements. The C++ vector::clear function is used to clear all elements of the vector. This function makes the vector empty with a size of zero.
Syntax for Vector clear() Function in C++
#include <vector> void clear() noexcept;
The function does not accept any parameter. The function does not return any type. Erases all elements from the container. To use vector, include <vector> header.
Complexity
Linear in size (destructions). This may be optimized to constant complexity for trivially-destructible types (such as scalar or PODs), where elements need not be destroyed.
Iterator validity
All iterators, pointers and references related to this container are invalidated.
Data races
The container is modified. All contained elements are modified.
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
/* clear all elements of the vector by vector::clear function code example */ #include <iostream> #include <vector> using namespace std; int main (){ vector<int> MyVector{10, 20, 30, 40, 50}; vector<int>::iterator it; cout<<"Before clear() function: \nMyVector contains:"; for(it = MyVector.begin(); it != MyVector.end(); ++it) cout<<" "<<*it; cout<<"\nMyVector size is: "<<MyVector.size()<<"\n\n"; MyVector.clear(); cout<<"After clear() function: \nMyVector contains:"; for(it = MyVector.begin(); it != MyVector.end(); ++it) cout<<" "<<*it; cout<<"\nMyVector size is: "<<MyVector.size(); return 0; }
Vector Library Operator Index [] in C++
Access element. Returns a reference to the element at position n in the vector container. A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception. Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.
Syntax for Vector Operator Index [] in C++
#include <vector> 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 vector. If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference. Member types reference and const_reference are the reference types to the elements of the container (see vector 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). The reference returned can be used to access or modify elements. Concurrently accessing or modifying different 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.
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 reference to the element at specified location pos. No bounds checking is performed. Unlike std::map::operator[], this operator never inserts a new element into the container. Accessing a nonexistent element through this operator is undefined behavior. */ /* Access element from a vector by vector::operator[] code example */ #include <iostream> #include <vector> int main () { std::vector<int> myvector (10); // 10 zero-initialized elements std::vector<int>::size_type sz = myvector.size(); // assign some values: for (unsigned i=0; i<sz; i++) myvector[i]=i; // reverse vector using operator[]: for (unsigned i=0; i<sz/2; i++) { int temp; temp = myvector[sz-1-i]; myvector[sz-1-i]=myvector[i]; myvector[i]=temp; } std::cout << "myvector contains:"; for (unsigned i=0; i<sz; i++) std::cout << ' ' << myvector[i]; std::cout << '\n'; return 0; }
Vector Library pop_back() Function in C++
Delete last element. Removes the last element in the vector, effectively reducing the container size by one. The C++ vector::pop_back function is used to delete the last element of the vector. Every deletion of element results into reducing the container size by one unless the vector is empty. This destroys the removed element.
Syntax for Vector pop_back() Function in C++
#include <vector> 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 iterating ranges that include the removed element is not.
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, 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
/* push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1. */ /* remove last element from vector and reduces size of vector by one with std::vector::pop_back() function code example. */ #include <iostream> #include <vector> using namespace std; int main (){ vector<int> MyVector{100, 200, 300, 400, 500, 600}; vector<int>::iterator it; //deletes last element of the vector MyVector.pop_back(); //deletes next last element of the vector MyVector.pop_back(); cout<<"The vector contains:"; for(it = MyVector.begin(); it != MyVector.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; }
Vector Library swap() Function in C++
Swap content. Exchanges the content of the container by the content of x, which is another vector object of the same type. Sizes may differ. After the call to this member function, the elements in this container are those which were in x before the call, and the elements of x are those which were in this. All iterators, references and pointers remain valid for the swapped objects. Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function.
Syntax for Vector swap() Function in C++
#include <vector> void swap (vector& x);
x
Another vector container of the same type (i.e., instantiated with the same template parameters, T and Alloc) whose content is swapped with that of this container. This function does not return any value. Whether the container allocators are also swapped is not defined, unless in the case the appropriate allocator traits indicate explicitly that they shall propagate. The bool specialization of vector provides an additional overload for this function (see vector::swap).
Complexity
Constant
Iterator validity
All iterators, pointers and references referring to elements in both containers remain valid, and are now referring to the same elements they referred to before the call, but in the other container, where they now iterate. Note that the end iterators do not refer to elements and may be invalidated.
Data races
Both the container and x are modified. No contained elements are accessed by the call (although see iterator validity above).
Exception safety
If the allocators in both vectors compare equal, or if their allocator traits indicate that the allocators shall propagate, the function never throws exceptions (no-throw guarantee). Otherwise, 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
/* exchange the elements specified in two vectors by vector::swap() function code example. */ // CPP program to illustrate implementation of swap() function #include <iostream> #include <vector> using namespace std; int main() { // vector container declaration vector<int> myvector1{ 1, 2, 3, 4 }; vector<int> myvector2{ 3, 5, 7, 9 }; // using swap() function to swap // elements of vector myvector1.swap(myvector2); // printing the first vector cout << "myvector1 = "; for (auto it = myvector1.begin(); it < myvector1.end(); ++it) cout << *it << " "; // printing the second vector cout << endl << "myvector2 = "; for (auto it = myvector2.begin(); it < myvector2.end(); ++it) cout << *it << " "; return 0; }
Vector Library begin() Function in C++
Return iterator to beginning. Returns an iterator pointing to the first element in the vector. Notice that, unlike member vector::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. The C++ function std::vector::begin() returns a random access iterator pointing to the first element of the vector.
Syntax for Vector begin() Function in C++
#include <vector> 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 vector 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 21 22
/* returns a random access iterator pointing to the first element of the vector by std::vector::begin() function code example. */ // CPP program to illustrate implementation of begin() function #include <iostream> #include <string> #include <vector> using namespace std; int main() { // declaration of vector container vector<string> myvector{ "This", "is", "HappyCodings" }; // using begin() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0; }
Vector Library end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector. 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 vector::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as vector::begin.
Syntax for Vector end() Function in C++
#include <vector> 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 vector 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). To use vector, include <vector> header. It does not point to the last element, thus to get the last element we can use vector::end()-1.
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
/* returns the iterator pointing to the past-the-last element of the vector container by vector::end function code example. */ // CPP program to illustrate implementation of begin() function #include <iostream> #include <string> #include <vector> using namespace std; int main() { // declaration of vector container vector<string> myvector{ "This", "is", "HappyCodings" }; // using begin() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0; }
Vector Library reserve() Function in C++
Request a change in capacity. Requests that the vector capacity be at least enough to contain n elements. The C++ function std::vector::reserve() requests to reserve vector capacity be at least enough to contain n elements. Reallocation happens if there is need of more space. If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater). In all other cases, the function call does not cause a reallocation and the vector capacity is not affected. This function has no effect on the vector size and cannot alter its elements.
Syntax for Vector reserve() Function in C++
#include <vector> void reserve (size_type n);
n
Minimum capacity for the vector. Note that the resulting vector capacity may be equal or greater than n. Member type size_type is an unsigned integral type. This function does not return any value. If the size requested is greater than the maximum size (vector::max_size), a length_error exception is thrown. If case of reallocation, the storage 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
If a reallocation happens, linear in vector size at most.
Iterator validity
If a reallocation happens, all iterators, pointers and references related to the container are invalidated. Otherwise, they all keep referring to the same elements they were referring to before the call.
Data races
If a reallocation happens, the container and all its contained elements are modified. Otherwise, the container is accessed, but not the contained elements: concurrently accessing or modifying them is safe.
Exception safety
If no reallocations happen or if the type of the elements has either a non-throwing move constructor or a copy constructor, 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). The function throws length_error if n is greater than max_size.
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
/* The C++ reserve() function helps us in reserving a vector capacity. This capacity must be enough so that it can contain n number of elements. This function can help us in increasing the capacity of any given vector which has a value greater than or equal to the new capacity which we will specify in the reserve function. The reserve function will just reserve the space for the vectors but will not increase its size. If the size, you are reserving in the vector is greater than the size then all these changes stand invalidated. */ /* request change in vector allocation by vector::reserve() function code example. */ #include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v1; vector<int> v2; ssize_t size; size = v1.capacity(); for (int i = 0; i < 25; ++i) { v1.push_back(i); if (size != v1.capacity()) { size = v1.capacity(); cout << "Expanding vector v1 to hold " << size << " elements" << endl; } } cout << endl << endl; /* Reserve space for 25 elements */ v2.reserve(25); for (int i = 0; i < 25; ++i) { v2.push_back(i); if (size != v2.capacity()) { size = v2.capacity(); cout << "Expanding vector v2 to hold " << size << " elements" << endl; } } return 0; }
Vector Library get_allocator() Function in C++
Get allocator. Returns a copy of the allocator object associated with the vector. The C++ function std::vector::get_allocator() returns an allocator associated with vector. public member function std::vector::get_allocator gets allocator.
Syntax for Vector get_allocator() Function in C++
#include <vector> allocator_type get_allocator() const noexcept;
No parameter is required. Function returns the allocator. Member type allocator_type is the type of the allocator used by the container, defined in vector as an alias of its second template parameter (Alloc).
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. Copying any instantiation of the default allocator 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++ vector::get_allocator function returns a copy of allocator object associated with the given vector. */ /* Get allocator by vector::get_allocator function code example */ #include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v = {1, 2, 3, 4, 5}; int *p = NULL; /* allocate memory to store 5 elements */ p = v.get_allocator().allocate(5); for (int i = 0; i < 5; ++i) p[i] = i + 1; for (int i = 0; i < 5; ++i) cout << p[i] << endl; 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; }
Vector Library max_size() Function in C++
Return maximum size. Returns the maximum number of elements that the vector can hold. The vector::max_size() is a built-in function in C++ STL which returns the maximum number of elements that can be held by the vector container. This is the maximum potential size the container can reach due to known system or library implementation limitations, but the container is by no means guaranteed to be able to reach that size: it can still fail to allocate storage at any point before that size is reached.
Syntax for Vector max_size() Function in C++
#include <vector> size_type max_size() const noexcept;
This function does not accept any parameter. Function returns the maximum number of elements a vector container can hold as content. 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
/* The C++ vector::max_size function returns the maximum number of elements the vector can hold. It returns the maximum potential size the vector can reach due to known system or library implementation limitations. */ // C++ program code example to illustrate the vector::max_size() function #include <bits/stdc++.h> using namespace std; int main() { // initialize a vector vector<int> vec; // returns the max_size of vector cout << "max_size of vector 1 = " << vec.max_size() << endl; vector<int> vec1; // returns the max_size of vector cout << "max_size of vector 2 = " << vec1.max_size() << endl; return 0; }
Vector Library assign() Function in C++
Assign vector content. Assigns new contents to the vector, replacing its current contents, and modifying its size accordingly. The C++ function std::vector::assign() assign new values to the vector elements by replacing old ones. It modifies size of vector if necessary. If memory allocation happens allocation is allocated by internal allocator.
Syntax for Vector assign() Function in C++
#include <vector> //range (1) template <class InputIterator> void assign (InputIterator first, InputIterator last); //fill (2) void assign (size_type n, const value_type& val); //initializer list (3) void assign (initializer_list<value_type> il);
first, last
Input iterators to the initial and final positions in a sequence. The range used is [first,last), which includes all the elements between first and last, including the element pointed by first but not the element 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.
n
New size for the container. Member type size_type is an unsigned integral type.
val
Value to fill the container with. Each of the n elements in the container will be initialized to a copy of this value. Member type value_type is the type of the elements in the container, defined in vector as an alias of its first template parameter (T).
il
An initializer_list object. The compiler will automatically construct such objects from initializer list declarators. Member type value_type is the type of the elements in the container, defined in vector as an alias of its first template parameter (T). This function does not return any value. In the range version (1), the new contents are elements constructed from each of the elements in the range between first and last, in the same order. In the fill version (2), the new contents are n elements, each initialized to a copy of val. In the initializer list version (3), the new contents are copies of the values passed as initializer list, in the same order. The internal allocator is used (through its traits) to allocate and deallocate storage if a reallocation happens. It is also used to destroy all existing elements, and to construct the new ones. Any elements held in the container before the call are destroyed and replaced by newly constructed elements (no assignments of elements take place). This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.
Complexity
Linear on initial and final sizes (destructions, constructions). Additionally, in the range version (1), if InputIterator is not at least of a forward iterator category (i.e., it is just an input iterator) the new capacity cannot be determined beforehand and the operation incurs in additional logarithmic complexity in the new size (reallocations while growing).
Iterator validity
All iterators, pointers and references related to this container are invalidated.
Data races
All copied elements are accessed. The container is modified. All contained elements are modified.
Exception safety
Basic guarantee: if an exception is thrown, the container is in a valid state. If allocator_traits::construct is not supported with the appropriate arguments for the element constructions, or if the range specified by [first,last) is not valid, 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 42 43 44 45 46 47 48 49
/* vector::assign() is a library function of "vector" header, it is used to initialize a vector or assign content to a vector, it assigns the new content to the vector, update the existing content, and also resizes the vector's size according to the content. */ /* assign new values to the vector and replacing the old ones by vector assign() function code example. */ #include <iostream> #include <vector> using namespace std; int main() { //declaring vectors vector<int> v1; vector<int> v2; vector<int> v3; //an array that will be used to assign a vector int arr[] = { 10, 20, 30, 40, 50 }; //assigning vectors //assigning v1 with 5 elements and 100 as default value v1.assign(5, 100); //assigning v1 with array v2.assign(arr + 0, arr + 5); //assigning v3 with vector v2 v3.assign(v2.begin(), v2.end()); //pritning the vectors cout << "v1: "; for (int x : v1) cout << x << " "; cout << endl; cout << "v2: "; for (int x : v2) cout << x << " "; cout << endl; cout << "v3: "; for (int x : v3) cout << x << " "; cout << endl; return 0; }
Vector Library rbegin() Function in C++
Return reverse iterator to reverse beginning. Returns a reverse iterator pointing to the last element in the vector (i.e., its reverse beginning). vector::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. 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 vector::back, which returns a reference to this same element, this function returns a reverse random access iterator.
Syntax for Vector rbegin() Function in C++
#include <vector> 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 vector 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 random access iterator types (pointing to an element and to a const element, respectively). See vector 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++ function std::vector::rbegin() returns a reverse iterator which points to the last element of the vector. */ /* Return the reverse iterator pointing to the last element of the vector by vector::rbegin function code example. */ #include <bits/stdc++.h> using namespace std; int main() { vector<int> v; v.push_back(11); v.push_back(12); v.push_back(13); v.push_back(14); v.push_back(15); // prints all the elements cout << "The vector elements in reverse order are:\n"; for (auto it = v.rbegin(); it != v.rend(); it++) cout << *it << " "; return 0; }
Vector Library empty() Function in C++
Test whether vector is empty. Returns whether the vector is empty (i.e. whether its size is 0). This function does not modify the container in any way. To clear the content of a vector, see vector::clear. Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::empty() is a library function of "vector" header, it is used to check whether a given vector is an empty vector or not, it returns a true if the vector size is 0, otherwise it returns false.
Syntax for Vector empty() Function in C++
#include <vector> bool empty() const noexcept;
This function does not accept any parameter. Function returns true if the container size is 0, false otherwise.
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 26 27 28 29 30 31 32 33 34 35 36 37
/* check whether the vector is empty or not by vector::empty function code example. */ //C++ STL program to demonstrate example of vector::empty() function #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1; //printing the size of the vector cout << "Total number of elements: " << v1.size() << endl; //checking whether vector is empty or not if (v1.empty()) cout << "vector is empty." << endl; else cout << "vector is not empty." << endl; //pushing elements v1.push_back(10); v1.push_back(20); v1.push_back(30); v1.push_back(40); v1.push_back(50); //printing the size of the vector cout << "Total number of elements: " << v1.size() << endl; //checking whether vector is empty or not if (v1.empty()) cout << "vector is empty." << endl; else cout << "vector is not empty." << endl; return 0; }
Vector Library insert() Function in C++
Insert elements. The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted. This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity. Because vectors use an array as their underlying storage, inserting elements in positions other than the vector end causes the container to relocate all the elements that were after position to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list). The parameters determine how many elements are inserted and to which values they are initialized:
Syntax for Vector insert() Function in C++
#include <vector> //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 vector 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 vector 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. If reallocations happen, the storage 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). The C++ function std::vector::insert() extends vector by inserting new element at position in container. Reallocation happens if there is need of more space. This function increases container size by one.
Complexity
Linear on the number of elements inserted (copy/move construction) plus the number of elements after position (moving). Additionally, if InputIterator in the range insert (3) is not at least of a forward iterator category (i.e., just an input iterator) the new capacity cannot be determined beforehand and the insertion incurs in additional logarithmic complexity in size (reallocations). If a reallocation happens, the reallocation is itself up to linear in the entire size at the moment of the reallocation.
Iterator validity
If a reallocation happens, all iterators, pointers and references related to the container are invalidated. Otherwise, only those pointing to position and beyond are invalidated, with all iterators, pointers and references to elements before position guaranteed to keep referring to the same elements they were referring to before the call.
Data races
All copied elements are accessed. The container is modified. If a reallocation happens, all contained elements are modified. Otherwise, none of the elements before position is accessed, and concurrently accessing or modifying them is safe (although see iterator validity above).
Exception safety
If the operation inserts a single element at the end, and no reallocations happen, there are no changes in the container in case of exception (strong guarantee). In case of reallocations, the strong guarantee is also given in this case if the type of the elements is either copyable or no-throw moveable. 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
/* extends vector by inserting new element at position in container by std::vector::insert() function code example. */ // program below illustrates the vector::insert() function #include <bits/stdc++.h> using namespace std; int main() { // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 one time at front auto it = vec.insert(vec.begin(), 1, 3); // inserts 4 two times at front vec.insert(it, 2, 4); cout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0; }
Vector Library erase() Function in C++
Erase elements. Removes from the vector either a single element (position) or a range of elements ([first,last)). This effectively reduces the container size by the number of elements removed, which are destroyed. Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).
Syntax for Vector erase() Function in C++
#include <vector> 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 vector. Member types iterator and const_iterator are random access iterator types that point to elements.
first, last
Iterators specifying a range within the vector] 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 the number of elements after the last element deleted (moving).
Iterator validity
Iterators, pointers and references pointing to position (or first) and beyond are invalidated, with all iterators, pointers and references to elements before position (or first) are guaranteed to keep referring to the same elements they were referring to before the call.
Data races
The container is modified. None of the elements before position (or first) is accessed, and concurrently accessing or modifying them is safe.
Exception safety
If the removed elements include 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). An invalid position or range 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 42
/* removes an element at specific index, or removes a range of elements from specific start to end indices by vector erase() function code example. */ //C++ STL program to demonstrate example of vector::erase() function #include <iostream> #include <vector> using namespace std; int main() { //vector declaration vector<int> v1{ 10, 20, 30, 40, 50 }; //printing elements cout << "v1: "; for (int x : v1) cout << x << " "; cout << endl; //removing one element v1.erase(v1.begin() + 2); //removes 2nd index element //printing elements after remove one element cout << "After removing one element..." << endl; cout << "v1: "; for (int x : v1) cout << x << " "; cout << endl; //removing a range of elements v1.erase(v1.begin() + 1, v1.begin() + 3); //removes 1,2 index elements //printing elements after remove one element cout << "After removing a range of elements..." << endl; cout << "v1: "; for (int x : v1) cout << x << " "; cout << endl; return 0; }
Vector 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 vector (which is considered its reverse end). The C++ vector::rend function returns the reverse iterator pointing to the element preceding the first element (reversed past-the-last element) of the vector. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the vector container. Similarly, decreasing a reverse iterator results into moving to the end of the vector container. The range between vector::rbegin and vector::rend contains all the elements of the vector (in reverse order).
Syntax for Vector rend() Function in C++
#include <vector> reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept;
This function does not accept any parameter. Function returns a reverse iterator to the reverse end of the sequence container. If the vector 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 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 21 22 23 24 25 26 27
/* vector::rend() is a library function of "vector" header, it is used to get the first element of a vector using reverse_iterator, it returns a reverse iterator pointing to the element preceding the first element (i.e. reverse ending) of a vector. */ /* Return reverse iterator to reverse end by vector rend() function code example */ #include <bits/stdc++.h> using namespace std; int main() { vector<int> v; v.push_back(11); v.push_back(12); v.push_back(13); v.push_back(14); v.push_back(15); cout << "The last element is: " << *v.rbegin(); // prints all the elements cout << "\nThe vector elements in reverse order are:\n"; for (auto it = v.rbegin(); it != v.rend(); 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; }
Vector Library back() Function in C++
Access last element. back() function returns a reference to the last element in the vector. vector::back() is a library function of "vector" header, it is used to access the last element from the vector, it returns a reference to the last element of the vector. Unlike member vector::end, which returns an iterator just past this element, this function returns a direct reference. Calling this function on an empty container causes undefined behavior.
Syntax for Vector back() Function in C++
#include <vector> reference back(); const_reference back() const;
This function does not accept any parameter. Function returns a reference to the last element in the vector. If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference. Member types reference and const_reference are the reference types to the elements of the vector.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). The reference returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, 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
/* The C++ function std::vector::back() returns a reference to the last element of the vector. Calling back on empty vector causes undefined behavior. */ /* Access last element in the vector by vector::back() function code example */ #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1{ 10, 20, 30, 40, 50 }; //accessing last element //using vector::back() function cout << "last element is: " << v1.back() << endl; //changing last element v1.at(v1.size() - 1) = 100; cout << "now, last element is: " << v1.back() << endl; //changing last element //using push_back() v1.push_back(200); cout << "now, last element is: " << v1.back() << endl; return 0; }
Vector Library front() Function in C++
Access first element. Returns a reference to the first element in the vector. The C++ function std::vector::front() returns a reference to the first element of the vector. Unlike member vector::begin, which returns an iterator to this same element, this function returns a direct reference. Calling this function on an empty container causes undefined behavior.
Syntax for Vector front() Function in C++
#include <vector> reference front(); const_reference front() const;
This function does not accept any parameter. Function returns a reference to the first element in the vector container. If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference. Member types reference and const_reference are the reference types to the elements of the container (see vector 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). The reference returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, 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
/* vector::front() is a library function of "vector" header, it is used to access the first element from the vector, it returns a reference to the first element of the vector. To use vector, include <vector> header. */ /* return a reference to the first element of the vector by C++ function std::vector::front() code example. */ // CPP program code example to illustrate application Of front() function #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1{ 10, 20, 30, 40, 50 }; //accessing first element //using vector::front() function cout << "first element is: " << v1.front() << endl; //changing first element v1.at(0) = 100; cout << "now, first element is: " << v1.front() << endl; return 0; }
Vector Library size() Function in C++
Return size. Returns the number of elements in the vector. This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity. vector::size() is a library function of "vector" header, it is used to get the size of a vector, it returns the total number of elements in the vector. The dynamic array can be created by using a vector in C++. One or more elements can be inserted into or removed from the vector at the run time that increases or decreases the size of the vector. The size or length of the vector can be counted using any loop or the built-in function named size().
Syntax for Vector size() Function in C++
#include <vector> 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
/* get the size of a vector, it returns the total number of elements in the vector by vector::size() library function. */ #include <bits/stdc++.h> using namespace std; int main() { // Initializing a vector of string type vector<string> vec = { "Happy", "8)", "Codings" }; // Clearing the vector // Now size is equal to 0 vec.clear(); // Typecasting vec.size() to int for (int i = 0; i < (int)vec.size() - 1; i++) cout << vec[i] << ' '; cout << "Happy8)Codings"; return 0; }
Vector Library capacity() Function in C++
Return size of allocated storage capacity. Returns the size of the storage space currently allocated for the vector, expressed in terms of elements. The vector::capacity() function is a built-in function which returns the size of the storage space currently allocated for the vector, expressed in terms of elements. This capacity is not necessarily equal to the vector size. It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion. Notice that this capacity does not suppose a limit on the size of the vector. When this capacity is exhausted and more is needed, it is automatically expanded by the container (reallocating it storage space). The theoretical limit on the size of a vector is given by member max_size. The capacity of a vector can be explicitly altered by calling member vector::reserve.
Syntax for Vector capacity() Function in C++
#include <vector> size_type capacity() const noexcept;
This function does not accept any parameter. Function returns the size of the currently allocated storage capacity in the vector, measured in terms of the number elements it can hold. 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
/* The C++ function std::vector::capacity() returns the size of allocate storage, expressed in terms of elements. This capacity is not necessarily equal to the size of vector. It can be equal or greater than vector size. The theoretical limit on vector size is given by member max_size.*/ // C++ program code example to illustrate the vector::capacity() function #include <bits/stdc++.h> using namespace std; int main() { vector<int> v; // inserts elements for (int i = 0; i < 100; i++) { v.push_back(i * 10); } cout << "The size of vector is " << v.size(); cout << "\nThe maximum capacity is " << v.capacity(); 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; }
Vector Library resize() Function in C++
Change size. Resizes the container so that it contains n elements. The vector is a very useful class of C++ for creating the dynamic array. The size of the vector can be changed at any time to solve any programming problem. Many built-in functions exist in C++ for doing the different types of tasks in a vector container. The resize() function is one of them. It is used to change the size of the vector. The vector size can be increased or decreased by using this function.
Syntax for Vector resize() Function in C++
#include <vector> 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 vector as an alias of the first template parameter (T). This function does not return any value. If a reallocation happens, the storage 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). 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. If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place. Notice that this function changes the actual content of the container by inserting or erasing elements from it.
Complexity
Linear on the number of elements inserted/erased (constructions/destructions). If a reallocation happens, the reallocation is itself up to linear in the entire vector size.
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, the end iterator is invalidated and, if it has to reallocate storage, all iterators, pointers and references related to this container are also invalidated.
Data races
The container is modified. If a reallocation happens, all contained elements are modified. Otherwise, none of the elements before n is accessed, and concurrently accessing or modifying them is safe.
Exception safety
If n is less than or equal to the size of the container, the function never throws exceptions (no-throw guarantee). If n is greater and a reallocation happens, there are no changes in the container in case of exception (strong guarantee) if the type of the elements is either copyable or no-throw moveable. Otherwise, if an exception is thrown, the container is left with a valid state (basic guarantee).
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
/* resize the container by specified number of elements (n) by vector::resize function code example */ // resizing of the vector #include <iostream> #include <vector> using namespace std; int main() { vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(4); cout << "Contents of vector after resizing:" << endl; // displaying the contents of the // vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0; }
Vectors in C++ Language
In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program.
Declaration for Vectors in C++
std::vector<T> vector_name;
The type parameter <T> specifies the type of the vector. It can be any primitive data type such as int, char, float, etc.
Initialization for Vectors in C++
// Vector initialization method 1 // Initializer list vector<int> vector1 = {1, 2, 3, 4, 5};
We are initializing the vector by providing values directly to the vector. vector1 is initialized with values 1, 2, 3, 4, 5.
// Vector initialization method 2 vector<int> vector3(5, 12);
Here, 5 is the size of the vector and 8 is the value. This code creates an int vector with size 5 and initializes the vector with the value of 8. So, the vector is equivalent to
vector<int> vector2 = {8, 8, 8, 8, 8};
The vector class provides various methods to perform different operations on vectors. Add Elements to a Vector: To add a single element into a vector, we use the push_back() function. It inserts an element into the end of the vector. Access Elements of a Vector: In C++, we use the index number to access the vector elements. Here, we use the at() function to access the element from the specified index. Change Vector Element: We can change an element of the vector using the same at() function. Delete Elements from C++ Vectors: To delete a single element from a vector, we use the pop_back() function. In C++, the vector header file provides various functions that can be used to perform different operations on a vector. • size(): returns the number of elements present in the vector. • clear(): removes all the elements of the vector. • front(): returns the first element of the vector. • back(): returns the last element of the vector. • empty(): returns 1 (true) if the vector is empty. • capacity(): check the overall size of a vector. Vector iterators are used to point to the memory address of a vector element. In some ways, they act like pointers.
Syntax for Vector Iterators in C++
vector<T>::iterator iteratorName;
We can initialize vector iterators using the begin() and end() functions. The begin() function returns an iterator that points to the first element of the vector. The end() function points to the theoretical element that comes after the final element of the vector.
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
/* Vectors in C++ language */ // C++ program to illustrate the capacity function in vector #include <iostream> #include <vector> using namespace std; int main() { vector<int> myvector; for (int i = 1; i <= 5; i++) myvector.push_back(i); cout << "Size : " << myvector.size(); cout << "\nCapacity : " << myvector.capacity(); cout << "\nMax_Size : " << myvector.max_size(); // resizes the vector size to 4 myvector.resize(4); // prints the vector size after resize() cout << "\nSize : " << myvector.size(); // checks if the vector is empty or not if (myvector.empty() == false) cout << "\nVector is not empty"; else cout << "\nVector is empty"; // Shrinks the vector myvector.shrink_to_fit(); cout << "\nVector elements are: "; for (auto it = myvector.begin(); it != myvector.end(); it++) cout << *it << " "; 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 << ' '; } }


Example of using this 'pointer' is to return the "Reference of current object" so that you can chain "function calls", this way you can call all the functions for the current object in one go.