Vector Type STL in C++

Vectors are sequence containers that work the same as variable-size Arrays. It is a kind of STL (Standard Template Library) based on a class template that can provide standard functionality like a Dynamic Array. Similarly, like an array, a vector can be of any type like a character array, integer array, boolean array, string array, etc. 

A Template is not a class or function it is like a blueprint or a guideline for the compiler to use the template to create a specific class or function. We specify which class to instantiate by supplying additional information depending on the template in our case we will specify the vector data type in between two angle brackets after the template name.

  • syntax: vector<datatype> vector_name;
  • example: vector<int> myvec;(alert-success)

In a vector, elements are in contiguous memory locations, and when we insert a value in a vector stored at the end. Removing or inserting values into a vector takes a constant amount of time and their size grows dynamically as their storage is handled by a container. We need to include a specific <vector> header file in our C++ program to use all the functionality of vector. 


Vector Functions.

There is a list of member functions available in the vector header file that we can directly use for solving our coding problems. Let's understand them one by one.

Iterator member functions:

Member Function Definition
begin() This function returns an iterator pointer pointing to the first element of the vector.
end() This function returns an iterator pointer pointing to the last element of the vector.
rbegin() This function returns a reverse iterator pointer pointing to the last element of the vector. It follows a reverse order and moves from the last element toward the first.
rend() This function returns a reverse iterator pointer pointing to the first element of the vector. It follows a reverse order and moves from the first element toward the last.
cbegin() This function returns a const_iterator pointing to the first element of the vector container. This const_iterator is used to point to a const value.
cend() This function returns a const_iterator pointing to the last element of the vector container. This const_iterator is used to point to a const value.
crbegin() This function returns a const_reverse_iterator pointing to the last element of the vector container.
crend() This function returns a const_reverse_iterator pointing to the first element of the vector container.

C++ Example Code:
//C++ Program to show iterator function of vector STL
#include<iostream>
#include<vector>
using namespace std;

int main(){
    //declaration of integer type vector
    vector<int> myVec;

    //inserting elements in vector
    for(int i = 0; i < 6; i++)
       myVec.push_back(i+2);

    cout<<"Printing values using begin() and end() fun: ";
    for(auto it = myVec.begin(); it != myVec.end(); it++)
       cout<<*it<<" ";  

    cout<<"\nPrinting values using rbegin() and rend(): ";
    for(auto it = myVec.rbegin(); it != myVec.rend(); it++)
       cout<<*it<<" ";

    cout<<"\nPrinting values using cbegin() and cend(): ";
    for(auto it = myVec.cbegin(); it != myVec.cend(); it++)
       cout<<*it<<" ";  

    cout<<"\nPrinting values using crbegin() and crend(): ";
    for(auto it = myVec.crbegin(); it != myVec.crend(); it++)
       cout<<*it<<" ";   

    return 0;        
}
Output:
Printing values using begin() and end() fun: 2 3 4 5 6 7
Printing values using rbegin() and rend(): 7 6 5 4 3 2
Printing values using cbegin() and cend(): 2 3 4 5 6 7
Printing values using crbegin() and crend(): 7 6 5 4 3 2


Vector Functions to Check Capacity.

Member Function Definition
size() This function returns the size of the vector or we can say it returns a number of elements present in the vector.
capacity() This function returns the current allocated storage space to the vector. This capacity might not be equal to the size of the vector.
shrink_to_fit() This function decreases the current capacity of the vector container and makes it equal to the size.
resize(n) This function changes the vector's current size to make it fit for n elements.
reserve() This function requests that the vector capacity be at least enough for n elements only when the current capacity is not enough for n elements.
empty() This function is used to check if the vector is empty or not or if the size is equal to 0 then it returns true else returns false.
max_size() This function gives us an idea about the maximum number of elements the vector can hold.

C++ Example Code:
//C++ Program to show capacity function of vector STL
#include<iostream>
#include<vector>
using namespace std;

int main(){
    //declaration of integer type vector
    vector<int> myVec;

    //inserting elements in vector
    for(int i = 0; i < 6; i++)
       myVec.push_back(i+2);

    if(!myVec.empty()){
        cout<<"Size: "<<myVec.size()<<endl;
        cout<<"Capacity: "<<myVec.capacity()<<endl;
        cout<<"Maximum Size: "<<myVec.max_size()<<endl;

        myVec.shrink_to_fit();
        cout<<"Capacity after shrinking: "<<myVec.capacity()<<endl;
    }
    else{
        cout<<"Vector is empty!!!"<<endl;
    } 

    cout<<"Elements present in the vector: ";
    for(auto it = myVec.begin(); it != myVec.end(); it++)
       cout<<*it<<" ";  

    return 0;        
}
Output:
Size: 6
Capacity: 8
Maximum Size: 230584300921363951
Capacity after shrinking: 6
Elements present in the vector: 2 3 4 5 6 7

Element Access member functions:

Member Function Definition
operator[i] This function returns a reference to the element at the position mentioned in the square bracket in the vector.
at(i) This function works the same as the previous one and returns a reference to the element present at position i in the vector.
front() This function returns a reference to the first element of the vector.
back() This function returns a reference to the first element of the vector.
data() This function returns a direct pointer to the memory array used internally by the vector to store its owned elements.

C++ Example Code:
//C++ Program to show Element access function of vector STL
#include<iostream>
#include<vector>
using namespace std;

int main(){
    //declaration of integer type vector
    vector<int> myVec;

    //inserting elements in vector
    for(int i = 0; i < 6; i++)
       myVec.push_back(i+2);

    cout<<"Elements present in the vector: ";
    for(auto it = myVec.begin(); it != myVec.end(); it++)
       cout<<*it<<" ";  

    cout<<"\nElement at position myVec[3]: "<<myVec[3]<<endl;
    myVec[3] = 10;
    cout<<"Element at position myVec[3]: "<<myVec.at(3)<<endl;

    cout<<"First element of vector: "<<myVec.front()<<endl;
    cout<<"Last element of vector: "<<myVec.back()<<endl;

    int *p = myVec.data();
    cout<<"First element of vector: "<<*p;

    return 0;        
}
Output:
Elements present in the vector: 2 3 4 5 6 7
Element at position myVec[3]: 5
Element at position myVec[3]: 10
First element of vector: 2
Last element of vector: 7
First element of vector: 2

Vector Modifier member functions.

Member Function Definition
push_back() This function is used to insert or add an element at the end of the vector.
pop_back() This function is used to delete an element from the end of the vector.
insert() This function is used to insert an element before the element at the specified position.
assign() This function is used to assign new values to the vector elements by replacing the old values.
erase() This function is used to remove a single element or a range of elements from a vector.
swap() This function is used to swap the values of one vector with the values of other vectors of the same type. The size of both vectors might not be the same.
clear() This function is used to remove all the elements of the vector and empty it.
emplace() This function is used to insert a new element at a specific position and extend the size of the vector by one.
emplace_back() This function is used to insert a new element at the end position and effectively extend the size of the vector by one.

C++ Example Code:
//C++ Program to show Element access function of vector STL
#include<iostream>
#include<vector>
using namespace std;

int main(){
    //declaration of integer type vector
    vector<int> myVec;

    //inserting elements in vector
    for(int i = 0; i < 6; i++)
       myVec.push_back(i+2);

    cout<<"Elements present in the vector: ";
    for(auto it = myVec.begin(); it != myVec.end(); it++)
       cout<<*it<<" ";  

    myVec.push_back(50);
    cout<<"\nLast Element after push_back: "<<myVec.back()<<endl;
    //removing the last element
    myVec.pop_back();
    cout<<"Last Element after pop_back: "<<myVec.back()<<endl;

    //inserting element at pos 4
    myVec.insert(myVec.begin()+3, 35);
    cout<<"Element at position 4: "<<myVec[4]<<endl;
    
    cout<<"Size of vector before emplace: "<<myVec.size()<<endl;
    myVec.emplace(myVec.begin()+4, 55);
    cout<<"Size of vector after emplace: "<<myVec.size()<<endl;

    myVec.clear();
    cout<<"Size of vector after clear: "<<myVec.size()<<endl;

    return 0;        
}
Output:
Elements present in the vector: 2 3 4 5 6 7
Last Element after push_back: 50
Last Element after pop_back: 7
Element at position 4: 5
Size of vector before emplace: 7
Size of vector after emplace: 8
Size of vector after clear: 0

Various operations that we perform on the vector has different time complexity like,
  • Accessing any random element takes a constant amount of time O(1).
  • Inserting or removing elements takes a linear amount of time O(n) except for the last element which takes a constant amount of time O(1).
  • Resizing the vector size in an operation like insert or emplace takes a linear amount of time O(n)
Next:

C++ Program to Make a Calculator using Switch Case.

In this post, we are going to understand how to write simple calculator program in C++ programming language using switch and break statement. 

Make a Calculator using Switch Case

Our calculator can perform operation like addition, substraction, multiplication and division. It is going to take two input value from the user and the arthematic operator as a single character to perform that particular operation of the input values. 

C++ Example Code for Calculator using Switch statement. 

//C++ Code to make calculator using switch statement
#include<iostream>
using namespace std;

int main(){

    float value1, value2, result;
    char opt;

    cout<<"Enter two values: ";
    cin>>value1>>value2;
    cout<<"Enter the operator: ";
    cin>>opt;

    switch (opt)
    {
    case '+':
        result = value1 + value2;
        cout<<value1<<" + "<<value2<<" = "<<result<<endl;
        break;
    case '-':
        result = value1 - value2;
        cout<<value1<<" - "<<value2<<" = "<<result<<endl;
        break;
    case '*':
        result = value1 * value2;
        cout<<value1<<" * "<<value2<<" = "<<result<<endl;
        break; 
    case '/':
        result = value1 / value2;
        cout<<value1<<" / "<<value2<<" = "<<result<<endl;
        break;       
    default:
        cout<<"Operator not found !!!"<<endl;
        break;
    }
    return 0;
}
Output:
Enter two values: 56 4
Enter the operator: /
56 / 4 = 14

In the above program, we use switch case to check which kind of operator user in providing as an input and based on the correct match of switch we are executing the piece of code written in that particular case. 

Once the operation is performed and it reach the break statement we come out of switch case statements and end the code execution. If any chance we enter any wrong and invalid operator then the default section of switch case will execute. 

Next:

Concatenate Two Strings and Literals in C++.

Concatenation is a process of linking two more strings together in a chain-like structure to form a bigger string. There are multiple ways of concatenating strings and here we are going to discuss all of them one by one with C++ example code.


In C++, we work with two different kinds of strings one is a C-type string which is also known as Character Array and another is a String Class and we have different methods to concatenate these strings. If you are not familiar with the difference between Character Array and String Class then you can check out our post Character Array Vs String Class in C++


Concatenate String Class Objects.

Using + operator: 

We can concatenate two strings easily just by using the simple '+' operator between two strings and it will return us a single concatenated string. 


C++ Example Code:

//C++ example program Concatenation two string
#include<iostream>
#include<string>
using namespace std;

int main(){
  
  string leftstr = "Welcome to ";
  string rightstr = "AlgoLesson";

  //concatenation
  string resultstr = leftstr + rightstr;
  cout<<resultstr<<endl;
  //leftstr = leftstr + rightstr
  leftstr += rightstr;
  cout<<leftstr<<endl;

  return 0;
}
Output:
Welcome to AlgoLesson
Welcome to AlgoLesson

In the above code, we have concatenated two string variables together using the plus operator (+) but when we try to concatenate a string with literals then we need to make sure that at least one operand must be of string type. Let's understand this point with the below example.
string str1 = "Hello";
string str2 = "World";
//OK concatenate successfully
string str3 = str1 + " AlgoLesson " + str2;

//Error - cannot add two string literals
string str4 = "Wrong" + "Concatenation";

//OK - Code execute from left to right 
string str5 = str1 + " Wrong" + " Concatenation";

//Error - One side of + operator must be a string type.
string str5 = "Wrong" + " Concatenation " + str1;

From the above example, we can understand that we cannot directly concatenate two string literals using the + operator. There must be a string one-string type operand at any one side of the + operator.  

Using append() string function:

We have one append() string member function that is also used to add the second string at the end of the first string and store the concatenated string into the first string. 

C++ Example Code:
//C++ program Concatenation two string using append()
#include<iostream>
#include<string>
using namespace std;

int main(){

  string first = "Hello";
  string second = "World";

  first.append(second);

  cout<<first<<endl;
  
  return 0;
}
Output:
HelloWorld

Concatenation C-type string (Character Array).

In C-type string, we have strcat() function that is available inside <string> header file in C++ programming language that appends one string at the end of another string. This function takes two arguments let's say str1 and str2 and then it copies all the character of str2 and add them at the end of str1.

syntax: strcat(str1, str2);

C++ Example Code:
//C++ program Concatenation C-type string
#include<iostream>
#include<cstring>
using namespace std;

int main(){

  char str1[10] = "Learning";
  char str2[10] = "Coding";

  strcat(str1, str2);
  cout<<str1<<endl;

  return 0;
}
Output:
LearningCoding
Note: C-type string does not support the use of operators on string that's one of the reason we cannot use + operator to concatenate two C-type or Character type string in C++. (alert-success)

Next:

C++ Program to Find Volume of Sphere.

A Sphere is a geometrical three-dimensional ball-like structure with no face. It is basically a set of points that are present at an equal distance from a given point in three-dimensional space and this equal distance r is known as the radius of the Sphere. 


In this post, we are going to learn how to calculate the volume of a sphere and how to implement the same in C++ programming.

The volume of any object is basically the amount of space that the object takes in three-dimensional space. The simple formula to calculate the volume of a sphere is shown below.

Find Volume of Sphere

C++ Example Code:

//C++ Code Implementation for Volume of Sphere
#include<iostream>
using namespace std;

int main(){
    int r;
    float volume;

    cout<<"Calculate the volume of the Sphere."<<endl;
    cout<<"Enter the radius of Sphere: ";
    cin>>r;

    volume = (4/3) * 3.14 * r * r * r;
    cout<<"The Volume of Sphere: "<<volume<<endl;

    return 0;
}
Output:
Calculate the volume of the Sphere.
Enter the radius of Sphere: 4.5
The volume of Sphere: 200.96 

Next:

C++ Program to Find Volume of a Cube.

A Cube is a geometrical three-dimensional shape formed by six equal square faces. It contains a total of 8 vertices and 12 similar size edges. If we consider the length of any one edge of the cube as a unit then the area of each face of the cube will be a^2. A Cube is a 3D object with length, breadth, and height the volume of a cube will be equal to length x breadth x height and as in our case, all sides are of equal length so the volume of our cube will be a^3.

Here in this post, we will find the volume of a cube with the help of C++ programming. 

C++ Example Code:

//C++ Code Implementation for Volume of Cube
#include<iostream>
using namespace std;

int main(){
    int a, volume;

    cout<<"Calculate the volume of the Cube."<<endl;
    cout<<"Enter the length of the side of Cube: ";
    cin>>a;

    volume = a * a * a;
    cout<<"The Volume of Cube: "<<volume<<endl;

    return 0;
}
Output:
Calculate the volume of the Cube.
Enter the length of the side of Cube: 6
The volume of Cube: 216

In the above code, we have used integer data type to calculate the volume of the cube but if you are dealing with decimal values then it is recommended to use float data type to calculate as it has the capability to represent decimal values.

Next:

Character Array Vs String Class in C++

Character Array and String Class are the two important topics of the C++ programming language and have their own use in many different situations. Both are used to deal with sequences of characters but many people get confused about finding the difference between them and when to use which one. 

String Class in C++ is introduced because there were many drawbacks to Character Array and you will be able to find it when you will read the difference between Character Array and String Class.

Character Array String Class
A character Array is an array used to store character-type data.

Ex: char ch[4] = "abc";
A string is a class in C++ programming and the string type variable is basically the object of the string class.

Ex: string str = "algolesson";
In character Array, we need to know the size of an array in advance. It string there is no need to know the size in advance. They adjust their size based on the requirement.
We cannot use C++ Operator on Character Array. We can use C++ Operator on String Class.
Operations like concatenation or append are difficult as a larger size Char array is required. An operation like concatenation or append are easier change in string size takes place automatically.
Character Arrays are much faster. Strings are slower as compared to the character array.

Example of Character Array code in C++:
//C++ example program for Character Array
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[]{"Algolesson"};

  cout<<ch<<endl;
  ch[4] = 'L';
  for(int i = 0; i < 11; i++){
    cout<<ch[i];
  }
  return 0;
}
Output:
Algolesson
AlgoLesson


The drawback of Character Array.

The main drawback of the Character array is that it fails to operate with the standard operators of C++ and they are not dynamic in nature as their sizes are fixed in advance and cannot change at run time. 
char ch1[]{"algolesson"}; //OK
ch1 = "coding"; //error- not OK

char ch2[]{"welcome"};
ch2 = ch1 + ch2; //error - we cannot use operator
  • Once the Character array is initialized with a set of characters then it cannot be initialized again with a different set of characters.
  • We cannot use + operators on Character Arrays in C++.

Although these above drawbacks of character array is removed in string class where we can easily increase our string size at run time and we can use several operators on string for comparison and manipulation task. There are many string member functions available in which helps us to perform operations on strings.

Example of String Class in C++:
//C++ example program for String Class
#include<iostream>
#include<string>
using namespace std;

int main(){
  string str1 = "Welcome to ";
  string str2 = "Algolesson";

  cout<<str1<<endl;
  cout<<str2<<endl;
  cout<<"Size of str1: "<<str1.size()<<endl;
  str1 = str1 + str2; //concatenation
  cout<<str1<<endl;
  cout<<"Size of str1: "<<str1.size()<<endl;

  return 0;
}
Output:
Welcome to 
Algolesson
Size of str1: 11
Welcome to Algolesson
Size of str1: 21

In the above code, we can observe that we can easily use operators on string data type and the size of str1 get automatically change after concatenation operation. This is how string class help us to overcome from the drawbacks of Character Array.

Next:

Difference Between Subarrays, Subsequences and Subsets.

In this post, we are going to understand the basic difference between Subarrays, Subsequences, and Subsets with respect to the Array data structure. These three terms are often used in coding problems and confused many of us which makes the question more difficult to understand. Let's discuss each term one by one with examples:


Subarrays: 

A subarray is a contiguous part of the main array in which the elements of the subarray are together and next to each other in relative order. If the given array has n number of elements then there can be n*(n + 1)/2 number of non-empty subarrays possible.

Example of Subarrays:

Given arr[ ] = {3, 5, 7, 2}
Total number of elements n = 4
The number of subarrays possible = n*(n+1)/2 = 4*(4+1)/2 = 4*5/2 = 10

List of all possible subarrays:
[3]
[5]
[7]
[2]
[3, 5]
[5, 7]
[7, 2]
[3, 5, 7]
[5, 7, 2]
[3, 5, 7, 2]


Subsequences:

A subsequence of an array contains elements in a relative order but need not to be a contiguous part of the main array. If the given array has n number of elements then there can be(2^n - 1)non-empty possible subsequences.

Example of Subsequences:
Given arr[ ] = {3, 5, 7, 2}
Total number of elements n = 4
The number of subsequences possible = 2^n - 1 = 2^4 - 1 = 15

List of all possible subsequences:
[3]
[5]
[7]
[2]
[3, 5]
[3, 7]
[3, 2]
[5, 7]
[5, 2]
[7, 2]
[3, 5, 7]
[3, 5, 2]
[3, 7, 2]
[5, 7, 2]
[3, 5, 7, 2]

Subsets:

The elements of a subset do not follow any relative order and may or may not be a contiguous part of the main array. If the given array has n number of elements then there can be(2^n) number of subsets possible. 

  • If array A is a subset of another array B then it means all the elements of array A must be present in array B. A ⊆ B

Example of Subsets:
Given A[] = {2, 3, 5} and B[] = {1, 2, 3, 4, 5, 6}

A ⊆ B as all the elements of A is present in B
Note: Every Subarray is a Subsequence and every Subsequence is a Subset but vice-versa is not true. (alert-success)


Next:

(getButton) #text=(Array Data Structure in C/C++) #icon=(link) #color=(#2339bd)

 

Program to Print Pascal's Triangle in Pattern.

Pascal Triangle is basically a triangular array formed by Binomial Coefficients. Here in this post, we will learn how to print Pascal Triangle using C++ programming language. Before going to the code section let us first understand the formation of the pascal triangle with one example.

Example of Pascal Triangle

If you observe the above triangular pattern carefully then you will observe that there is a rule for creating this Pascal Triangle. 
The rule for creating a Pascal Triangle is to start with the number 1 at level 0 and to get your next number for the following levels you need to add the two consecutive numbers that are present on the above left and above right side of it. (alert-success)
 1    2
 \ + /
 3

Approach 1: Using O(n^2) extra space.

Here we are going to use one extra 2D array to store the previously generated values so we can use them to calculate binomial coefficient values for the next upcoming rows. Sum the two above two consecutive numbers to get the next number.


C++ Code for Printing Pascal Triangle:

//C++ Program to Print Pascal Triangle using O(n^2) extra space
#include<iostream>
using namespace std;

void pascalTriangle(int n){
    int arr[n][n];

    cout<<"Print Pascal Triangle: "<<endl;
    for(int i = 0; i < n; i++){
        for(int j = 1; j < (n - i); j++){
            cout<<" ";
        }
        for(int k = 0; k <= i; k++){
            if(i == k || k == 0){
                arr[i][k] = 1;
            }
            else{
                arr[i][k] = arr[i - 1][k - 1] + arr[i - 1][k];
            }
            cout<<" "<<arr[i][k];
        }
        cout<<"\n";
    }
}
int main(){
    int n = 5;
    pascalTriangle(n);
}
Output:
Print Pascal Triangle:  
                  1
 
               1      1
 
            1      2      1
 
         1      3      3      1
 
      1      4      6      4      1
  • Time Complexity: (n^2)
  • Space Complexity: (n^2)

Approach 2: Without using extra Space.

Here we are simply using going to run two nested loops and going to calculate the binomial coefficient using the below formula in the inner loop. 
binomial coefficient

 C++ Code for Printing Pascal Triangle:

//Print Pascal Triangle in without using extra space in C++
#include<iostream>
using namespace std;

void pascalTriangle(int n){
    int row = n;

    cout<<"Print Pascal Triangle: "<<endl;;
    for(int i = 0; i < row; i++){
        int value = 1;
        for(int j = 1; j < (row -i); j++){
            cout<<" ";
        }
        for(int k = 0; k <= i; k++){
            cout<<" "<<value;
            value = value * (i - k)/(k + 1);
        }
        cout<<endl<<endl;
    }
}

int main(){
    int n = 5;
    pascalTriangle(n);

    return 0;
}
Output:
Print Pascal Triangle:  
                  1
 
               1      1
 
            1      2      1
 
         1      3      3      1
 
      1      4      6      4      1
  • Time Complexity: (n^2)
  • Space Complexity: (1)
I hope you found this post useful, please do share your valuable feedback in the comment section below and help us improve our content for you.

Next:

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson