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

Algorithm fill - Initializes every item in a range to value.

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
Algorithm fill - Initializes every item in a range to value. fill Header <algorithm> template<class ForwardIterator, class T> void fill(ForwardIterator first, ForwardIterator last, const T& value) Initializes every item in a range to value. Assigns value to each element in the range [first, last). Sample #pragma warning (disable:4786) #include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> vi(10) ; //intialize vector std::fill(vi.begin(), vi.end(), 0) ; std::ostream_iterator<int> intOstreamIt(std::cout, ", ") ; std::cout << "vi = " ; std::copy(vi.begin(), vi.end(), intOstreamIt ) ; std::cout << std::endl ; return 0 ; } Program Output vi = 0, 0, 0, 0, 0, 0, 0, 0, 0, 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; }
Algorithm Library copy() Function in C++
copy() function is used to copy items from one iterator to another iterator with a specific range. We can define the start and end position of the source and it will copy all items in this rage to a different destination. To use copy() function, we need to include <bits/stdc+.h> or header file. It copies all the elements pointed by first and last. first element is included in the output but last is not. output is the start position of the final result iterator. It returns one iterator to the end of the destination range where elements have been copied.
Syntax for copy() Function in C++
template <class InputIterator, class OutputIterator> OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);
first
It is an input iterator to the first element of the range, where the element itself is included in the range.
last
It is an input iterator to the last element of the range, where the element itself is not included in the range. Input iterators to the initial and final positions in a sequence to be copied. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
result
It is an output iterator to the first element of the new container in which the elements are copied. Output iterator to the initial position in the destination sequence. This shall not point to any element in the range [first,last). Function returns an iterator to the end of the destination range where elements have been copied.
Complexity
Linear in the distance between first and last: Performs an assignment operation for each element in the range.
Data races
The objects in the range [first,last) are accessed (each object is accessed exactly once). The objects in the range between result and the returned value are modified (each object is modified exactly once).
Exceptions
Throws if either an element assignment or an operation on iterators throws. Note that invalid arguments cause undefined behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* copying the array elements to the vector by copy() function code example */ // C++ STL program to demonstrate use of std::copy() function #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { //declaring & initializing an int array int arr[] = { 10, 20, 30, 40, 50 }; //vector declaration vector<int> v1(5); //copying array elements to the vector copy(arr, arr + 5, v1.begin()); //printing array cout << "arr: "; for (int x : arr) cout << x << " "; cout << endl; //printing vector cout << "v1: "; for (int x : v1) cout << x << " "; cout << endl; return 0; }
Algorithm Library fill() Function in C++
Fill range with value. Assigns val to all the elements in the range [first,last). C++ Algorithm fill() function is used to assign the same new value to every element in a specified range[first, end) by using operator=. fill() function is a library function of algorithm header, it is used to assign a value to the all elements within a given range of a container, it accepts iterators pointing to the starting and ending position in the container and a value to be assigned to the elements within the given range, and assigns the value.
Syntax for fill() Function in C++
#include <algorithm> template <class ForwardIterator, class T> void fill (ForwardIterator first, ForwardIterator last, const T& val);
first, last
Forward iterators to the initial and final positions in a sequence of elements that support being assigned a value of type T. The range filled is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
val
Value to assign to the elements in the filled range. This function does not return any value.
Complexity
Linear in the distance between first and last: Assigns a value to each element.
Data races
The objects in the range [first,last) are modified (each object is accessed exactly once).
Exceptions
Throws if either an element assignment or an operation on an iterator throws. Note that invalid arguments cause undefined behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/* fill() function is a library function of algorithm header, it is used to assign a value to the all elements within a given range of a container, it accepts iterators pointing to the starting and ending position in the container and a value to be assigned to the elements within the given range, and assigns the value. */ /* Assign val to all the elements in the range [first,last) by std::algorithm::fill() function code example. */ #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { //vector vector<int> v(10); //filling all elements with -1 fill(v.begin(), v.end(), -1); //printing vector elements cout << "v: "; for (int x : v) cout << x << " "; cout << endl; //filling initial 3 elements with 100 fill(v.begin(), v.begin() + 3, 100); //printing vector elements cout << "v: "; for (int x : v) cout << x << " "; cout << endl; //filling rest of the elements with 200 fill(v.begin() + 3, v.end(), 200); //printing vector elements cout << "v: "; for (int x : v) cout << x << " "; cout << endl; return 0; }
#include Directive in C++
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
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; }
Class Templates in C++
Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration.
Declaration for Class Template in C++
template <class T> class className { private: T var; ... .. ... public: T functionName(T arg); ... .. ... };
T
template argument
var
a member variable T is the template argument which is a placeholder for the data type used, and class is a keyword. Inside the class body, a member variable var and a member function functionName() are both of type T. Creating a class template object: Once we've declared and defined a class template, we can create its objects in other classes or functions (such as the main() function) with the following syntax:
className<dataType> classObject;
Defining a class member outside the class template: Suppose we need to define a function outside of the class template. We can do this with the following code:
template <class T> class ClassName { ... .. ... // Function prototype returnType functionName(); }; // Function definition template <class T> returnType ClassName<T>::functionName() { // code }
Notice that the code template <class T> is repeated while defining the function outside of the class. This is necessary and is part of the syntax. C++ class templates with multiple parameters: In C++, we can use multiple template parameters and even use default arguments for those parameters.
template <class T, class U, class V = int> class ClassName { private: T member1; U member2; V member3; ... .. ... public: ... .. ... };
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
/* Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function. */ #include <iostream> using namespace std; template <typename T> class Array { private: T *ptr; int size; public: Array(T arr[], int s); void print(); }; template <typename T> Array<T>::Array(T arr[], int s) { ptr = new T[s]; size = s; for(int i = 0; i < size; i++) ptr[i] = arr[i]; } template <typename T> void Array<T>::print() { for (int i = 0; i < size; i++) cout<<" "<<*(ptr + i); cout<<endl; } int main() { int arr[5] = {1, 2, 3, 4, 5}; Array<int> a(arr, 5); a.print(); return 0; }
Iterator Library ostream_iterator in C++
Ostream iterators are output iterators that write sequentially to an output stream (such as cout). They are constructed from a basic_ostream object, to which they become associated, so that whenever an assignment operator (=) is used on the ostream_iterator (dereferenced or not) it inserts a new element into the stream. Optionally, a delimiter can be specified on construction. This delimiter is written to the stream after each element is inserted.
Syntax for Iterator ostream_iterator in C++
#include <iterator> template <class T, class charT=char, class traits=char_traits<charT> > class ostream_iterator;
T
Element type for the iterator: The type of elements inserted into the stream
charT
First template parameter of the associated basic_ostream object: The type of elements the stream handles (char for ostream).
traits
Second template parameter of the associated basic_ostream: Character traits for the elements the stream handles. The default template arguments correspond to an instantiation that uses an ostream object as associated stream.
Member types
Member types & definition in istream_iterator ostream_type: basic_ostream<charT,traits> --- Type of the associated output stream iterator_category: output_iterator_tag --- Input iterator value_type: void char_type: charT --- Type of the characters handled by the associated stream traits_type: traits --- Character traits for associated stream difference_type: void pointer: void reference: void
Member functions
• (constructor) Construct ostream iterator (public member function ) • operator* Dereference iterator (public member function ) • operator++ Increment iterator (public member function ) • operator= Assignment operator (public member function )
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
/* C++ ostream_iterator is a special output iterator that write sequentially to an output stream. */ /* ostream_iterator class template - Output iterator to write items to an ostream */ /* C++ code example to illustrate read a bunch of strings from a file sort them lexicographically and print them to output stream */ #include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <vector> using namespace std; int main() { // Define a vector to store the strings received from input vector<string> strings_v; // Define the filestream object used to read data from file ifstream fin("input_file.txt"); // Get input stream and end of stream iterators istream_iterator<string> fin_it(fin); istream_iterator<string> eos; // Get output stream iterators ostream_iterator<string> cout_it(cout, " "); // Copy elements from input to vector using copy function copy(fin_it, eos, back_inserter(strings_v)); // Sort the vector sort(strings_v.begin(), strings_v.end()); // Copy elements from vector to output copy(strings_v.begin(), strings_v.end(), cout_it); 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; }
Function Templates in C++
A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values.
Syntax for Function Templates in C++
template < class Ttype> ret_type func_name(parameter_list) { // body of function. }
Ttype
a placeholder name
class
specify a generic type Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration. • Generic functions use the concept of a function template. Generic functions define a set of operations that can be applied to the various types of data. • The type of the data that the function will operate on depends on the type of the data passed as a parameter. • For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an array of integers or array of floats. • A Generic function is created by using the keyword template. The template defines what function will do. Function templates with multiple parameters: We can use more than one generic type in the template function by using the comma to separate the list.
template<class T1, class T2,.....> return_type function_name (arguments of type T1, T2....) { // body of function. }
Overloading a function template: We can overload the generic function means that the overloaded template functions can differ in the parameter list. Generic functions perform the same operation for all the versions of a function except the data type differs.
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
/* function templates in C++ language */ /* adding two numbers using function templates */ #include <iostream> using namespace std; template <typename T> T add(T num1, T num2) { return (num1 + num2); } int main() { int result1; double result2; // calling with int parameters result1 = add<int>(2, 3); cout << "2 + 3 = " << result1 << endl; // calling with double parameters result2 = add<double>(2.2, 3.3); cout << "2.2 + 3.3 = " << result2 << endl; 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; }
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; }


"Constructor" is automatically called when an object create. It is "special member function" of the class. Variable declaration, constructor without argument, and which constructor has
"Quicksort" is an Efficient Sorting Algorithm, serving as systematic method for placing the elements of an array in order. 'Quicksort' can operate 'in-place' on an array, requiring small