Site icon DataFlair

C++ Vector | Learn 5 Types of Functions Associated with Vector

Free C++ course with real-time projects Start Now!!

A vector in C++ is one of the most basic concepts of its Standard Template Library. Programming in C++ is incomplete without possessing the knowledge of vectors. C++ Vectors are nothing but arrays that are dynamic in nature which means that vectors possess the ability to change their size anytime during program run.

Before we begin, it is important to have a basic idea of Arrays in C/C++.

C++ Vector

Vectors are basically a data structure that not only acts as a dynamic array but also ensures quick and random access of elements pertaining to that vector.

We can easily insert, delete, traverse, and modify elements as well as manage computer memory required to store these with the help of the C++ sequence container.

Just like arrays, vectors are stored in contiguous memory locations for easy traversal with the help of iteration.

Note: It is important to note that Vector in C++ is totally different from Vectors in mathematics.

Key takeaway: We need to include the header file #include<vector> in order to access the Standard Template Library functions associated with vectors.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

Let us first discuss the basic syntax and the components of vectors before moving on to a C++ program.

Definition

Here is a definition of std::vector

template < class T, class Alloc = allocator<T> > class vector;

Now, let us discuss each component:

C++ Vectors Example

In order to acquaint ourselves with vectors, let us consider a very simple program to insert elements into the vector in C++:

#include <iostream> 
#include <vector> 
using namespace std;

int main() 
{

vector <string> v;

v.push_back("Welcome "); 
v.push_back("to "); 
v.push_back("DataFlair "); 
v.push_back("tutorials! ");

for(vector<string>::iterator i=v.begin();i!=v.end();++i) 
cout<<*i; 
return 0; 
}

Code-

Output-

Importance of C++ Vector

Unlike arrays, vectors are dynamic in nature that helps in efficient memory management.

Moreover, there are several member functions associated with vectors that help you ease out your way in manipulation and modification operations like insertion, deletion, traversal from the beginning, end, or middle of the vector.

Another advantage of vectors over arrays is that we create a dynamic array, we need to explicitly deallocate memory whereas, in a vector, the memory is automatically deallocated in the heap memory.

Unveil the Important Concepts – Multi-dimensional Arrays in C/C++ (2D & 3D Arrays)

Data Manipulation Operations on C++ Vector

As discussed earlier, it is pretty easy to perform data manipulation operations on Vectors.

Let us now discuss functions associated to perform different operations and the time taken by them:

  1. Insertion: Normally, if we want to insert an element into the vector, it is done from its rear end. We need to use the v.back() function in order to insert an element in the vector. This operation consumes differential time as there may be a need for extending the vector. If we wish to insert an element at the beginning or in the middle, it takes linear time.
  2. Deletion: Normally, if we talk about deleting an element from the vector, we do it from the rear end. We need to use the v.pop_back() function to delete an element from the rear end. It takes constant time as it is evident that no resizing of the vector takes place. If we wish to delete an element at the beginning or in the middle, it takes linear time.

Functions Correlated to C++ Vector

When we talk about member functions of vectors, there are basically 5 categories of functions associated with C++ vectors. The major operations on vectors are based on iteration, capacity, element access control, and modifiers.

On the other hand, when talking about non-member functions, there are only 2 vector functions available in the Standard Template Library.

Enhance your fundamental skills with Functions in C/C++ 

Types of Function Correlated to Vectors

  1. Iterator Functions
  2. Capacity Control Functions
  3. Element Access Control Functions
  4. Modifier Functions
  5. Allocator Functions

1. Iterator Functions

Example of Iterator Function in C++

Here is a C++ program that illustrates the use of these iterator functions:

#include <iostream> 
#include <vector> 
using namespace std; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

vector<int> v; 

for (int i = 1; i <= 10; i++) // Inserting elements from 10 to 20 in the vector
v.push_back(i); 

cout<<"Using begin() and end(): "; 
for (auto i = v.begin(); i != v.end(); ++i) 
cout<< *i << "\t"; 

cout<<endl<<"Using cbegin() and cend(): "; 
for (auto i = v.cbegin(); i != v.cend(); ++i) 
cout<< *i << "\t";

// Reversal operations 
cout<<endl<<"Using rbegin() and rend(): "; 
for (auto j = v.rbegin(); j != v.rend(); ++j) 
cout << *j << "\t"; 

cout<<endl<<"Using crbegin() and crend(): "; 
for (auto j = v.crbegin(); j != v.crend(); ++j) 
cout << *j << "\t"; 

return 0; 
}

Code-

Output-

2. Capacity Control Functions

Have you learned Virtual Function in C++?

Example of Capacity Control Function in C++

Here is a C++ program that illustrates the use of these capacity control functions:

#include <iostream> 
#include <vector> 
using namespace std; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

vector<int> v; 

for (int i = 1; i <= 10; i++) 
v.push_back(i);

// Function to find the capacity of the vector
cout<<endl<<"The capacity of the vector is: " << v.capacity();

// Conditional statement to check if the vector is empty or not 
if (v.empty() == false) 
cout<<endl<<"The vector is not empty "<<endl;
else
cout<<endl<<"The vector is empty "<<endl; 
cout << "Size : " << v.size(); 

// Function to find the max size of the vector 
cout<<endl<<"The max size of the vector is: " << v.max_size(); 

// Function to resize the vector size to 5 
v.resize(5); 

// Function to print the vector size after using resize() 
cout<<endl<<"The size of the vector is: " << v.size(); 

// Function to shrink the vector 
v.shrink_to_fit(); 
cout<<endl<<"The elements in the Vector are: "; 
for (auto j = v.begin(); j != v.end(); j++) 
cout << *j << "\t"; 

return 0; 
}

Code-

Output-

3. Element Access Control Functions

An Important Ingredient for a successful Programmer is Inline Function in C++

Example of Element Access Control Function in C++

Here is a C++ program that illustrates the use of these element access control functions:

#include <iostream>
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

vector<int> v; 

for (int i = 1; i <= 10; i++) // Inserting elements 10, 20, 30, ..... , 100
v.push_back(i * 10); 

cout<<endl<<"Using the Reference operator [n] : n1[5] = " << v[5]; 

cout<<endl<<"Using the at(n) function : at(3) = " << v.at(3); 

cout<<endl<<"Using the front() function : front() = " << v.front(); 

cout<<endl<<"Using the back() function: back() = " << v.back(); 


int* position = v.data(); // Pointer to the first element 

cout<<endl<<"The first element of the vector is " << *position <<endl;
return 0; 
}

Code-

Output-

4. Modifier Functions

Example of Modifier Function in C++

Here is a C++ program that illustrates the use of these modifier functions:

#include <iostream>
#include <bits/stdc++.h> 
#include <vector> 
using namespace std; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

vector<int> v; 

v.assign(5, 2); // Inserting the element "2" five times in the vector

cout<<"The elements in the vector are: "; 
for(int i = 0; i < v.size(); i++) 
cout << v[i] << "\t"; 

v.push_back(32); // Inserting the element "32" at the last position
int n = v.size(); 
cout<<endl<<"The last element of the vector is: " << v[n - 1];

v.pop_back(); // Removing the last element of the vector

// Displaying the elements of the vector 
cout<<endl<<"The vector elements are: "; 
for(int i = 0; i < v.size(); i++) 
cout << v[i] << "\t"; 

v.insert(v.begin(), 64); // Inserting "64" at the front in the vector

cout<<endl<<"The first element of the vector is: " << v[0]; 

v.erase(v.begin()); // Removing the first element from the vector

cout<<endl<<"The first element of the vector is: " << v[0]; 

v.emplace(v.begin(), 32); // Inserting element at the beginning of the vector
cout<<endl<<"The first element of the vector is: " << v[0]; 


v.emplace_back(30); // Inserting "30" at the end of the vector
n = v.size(); 
cout<<endl<<"The last element of the vector is: " << v[n - 1]; 

v.clear(); // Erasing the vector 
cout<<endl<<"The size of the vector after erasing is: " << v.size(); 

// Swapping vectors 
vector<int> v1, v2; 
v1.push_back(100); 
v1.push_back(200); 
v2.push_back(300); 
v2.push_back(400); 

cout<<endl<<"The first vector is : "; 
for (int i = 0; i < v1.size(); i++) 
cout << v1[i] << "\t"; 

cout<<endl<<"The second vector is : "; 
for (int i = 0; i < v2.size(); i++) 
cout << v2[i] << "\t"; 

// Swapping v1 with v2 
v1.swap(v2); 

cout<<endl<<"After swapping the first Vector: "; 
for (int i = 0; i < v1.size(); i++) 
cout << v1[i] << "\t"; 

cout<<endl<<"After swapping the second Vector 2: "; 
for (int i = 0; i < v2.size(); i++) 
cout << v2[i] << "\t";

return 0;
}

Output-

5. Allocator Functions

In the C++ Standard Template Library, sequence containers can change size dynamically. An allocator is basically an object that is responsible for dynamic memory allocation and deallocation.

In C++ vectors, there is only one function to achieve this task. This function is called the get_allocator() function. We use the get_allocator() to allocate chunks of memory which returns a copy of the allocator object associated with the container.

Quiz on C++ Vector

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 3; i++)

            v.push_back(i);

     

        for (auto i = v.begin(); i != v.end(); ++i)

            cout << *i << ” “;

     

        return 0;

    }

     

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 3; i++)

            v.push_back(i);

     

        for (auto i = v.rbegin(); i != v.rend(); ++i)

            cout << *i << ” “;

     

        return 0;

    }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 3; i++)

            v.push_back(i);

     

        cout << v.size()<<” “;

        cout << v.capacity()<<” “;

        return 0;

    }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 3; i++)

            v.push_back(i);

        v.resize(2);

        cout << v.size()<<” “;

     

        return 0;

    }

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 3; i++)

            v.push_back(i);

        cout << v.at(3);

     

        return 0;

    }

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 3; i++)

            v.push_back(i);

        cout << v.at(2);

     

        return 0;

    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 3; i++)

            v.push_back(i);

        cout << v.front()<<” “<<v.back();

     

        return 0;

    }

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 3; i++)

            v.push_back(i);

        v.assign(2,5);

        for (auto i = v.begin(); i != v.end(); ++i)

            cout << *i << ” “;

     

        return 0;

    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 2; i++)

            v.push_back(i);

        v.insert(v.begin(), 5);

        for (auto i = v.begin(); i != v.end(); ++i)

            cout << *i << ” “;

     

        return 0;

    }

     

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    #include <iostream>

    #include <vector>

      

    using namespace std;

      

    int main()

    {

        vector<int> v;

      

        for (int i = 1; i <= 2; i++)

            v.push_back(i);

        v.emplace_back(4);

        for (auto i = v.begin(); i != v.end(); ++i)

            cout << *i << ” “;

     

        return 0;

    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

     Which among the following is the disadvantage of vectors?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

     Out of all the options below which data structure has the easiest insertion and deletion operation?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    what is the operation of begin()?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    what is the operation of end()?

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    what is the operation of cbegin()?

    Correct
    Incorrect

Summary

As we learned C++ vectors are a data structure that not only acts as a dynamic array but also ensures quick and random access of elements pertaining to that vector. Now, you can easily insert, delete, traverse, and modify elements as well as manage computer memory. Vectors are an important concept for every C++ professional.

Get ready to Explore Function and Operator Overloading in C++ and become an expert in 7 Min

Suggestions and feedback are welcomed in the comment section!

Exit mobile version