When it comes to programming in C++, vectors are an essential data structure that every developer should be familiar with. Vectors provide a dynamic array-like structure that can store and manipulate elements efficiently. Whether you are a beginner or an experienced programmer, understanding vectors in C++ is crucial for building robust and flexible applications.
In this blog, we will explore the concept of vectors in C++ and delve into their various functionalities, including how to create and initialize vectors, access and modify elements, perform common operations, and utilize some advanced features. By the end of this blog, you will have a solid understanding of vectors and be equipped with the knowledge to leverage their power in your own C++ programs.
STL stands for Standard Template Library. STL is a set of general-purpose classes and functions mainly for storing and processing data. STL can be defined as a library of container classes, algorithms, and iterators, and vectors in C++ is part of STL. The main idea behind STL is to reuse codes already written and tested. It saves time and effort.
STL has four components
- Algorithms: It defines a collection of functions specially designed to be used on ranges of elements. Examples are sorting, searching, etc.
- Containers: Containers store objects and data. There are in total seven standard “first-class” container classes and three container adaptor classes and only seven header files that provide access to these container adaptors.
- Functions: STL includes classes which overload the function call operator. Instances of such classes are called functors.
- Iterators: It is used for working upon a sequence of values.It provides generiality in STL.
What are Vectors in C++?
Vectors are part of STL. Vectors in C++ are sequence containers representing arrays that can change their size during runtime. They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.
Vectors are the dynamic arrays that are used to store data.It is different from arrays which store sequential data and are static in nature, Vectors provide more flexibility to the program. Vectors can adjust their size automatically when an element is inserted or deleted from it.
Vectors are not ordered in C++. Vector elements are placed in adjacent storage and can be easily accessed and traversed across using iterators. In vectors, data is inserted at the end when we use push_back() function . Inserting an element at the end of a vector takes differential time, as sometimes there may be a need of extending the vector, but inserting the element at the beginning or at the middle takes linear time. Removing the last element takes only constant time because no resizing takes place. Check out this free online C++ tutorial to learn more and enhance your skills.
Declaration of Vectors in C++
It is mandatory to include #include<vector> library before using vectors in C++.
For Vector declaration we need to follow the below syntax:
vector< object_type > vector_variable_name;
Initialization of Vectors
- Pushing the values one-by-one in vector using push_back():
- All the elements that need to be stored in the vector are pushed back one-by-one in the vector using the push_back() method.
- Syntax:
vector_name.push_back(element_value);
- Using the overload constructor of the vector Class:
- This method is used to populate a vector with multiple times the same value.
- Syntax:
vector<object_type> vector_name (number_of_repetition,element_value);
- Using Array:
- This method uses array as a parameter to be passed in the vector constructor.
- Syntax:
vector<object_type> vector_name {val1,val2,val3,....,valn};
- Using already initialized vector:
- This method uses an already created vector to create a new vector with the same values.
- This method passes the begin() and end() of an already initialized vector.
|
Syntax:
vector<object_type> vector_name_1{val1,val2,…,valn};
vector<object_type> vector_name_2(vector_name_1.begin(),vector_name_1.end())
Various Functions in Vectors are
Iterators:
- begin() – It returns an iterator pointing to the first element in the vector.
- end() – It returns an iterator pointing to the last element in the vector.
- rbegin() – It returns a reverse iterator pointing to the last element in the vector.
- rend() – It returns a reverse iterator pointing to the element preceding the first element in the vector. Basically considered as a reverse end.
- cbegin() – It returns a constant iterator pointing to the first element in the vector.
- cend() – It returns a constant iterator pointing to the element that follows the last element in the vector.
- crbegin() – It returns a constant reverse iterator pointing to the last element in the vector.
- crend() – It returns a constant reverse iterator pointing to the element preceding the first element in the vector.
Example Code for Visualizing the use of Iterators:
//C++ Code to Visualize Use of Iterators in C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a; //Declaration of vector in C++
//Initializing vector ‘a’ with values from 1 to 7
for (int i = 1; i <=7 ; i++)
a.push_back(i);
//Printing the Output of vector ‘a’ using iterators begin() and end()
cout << "Output of begin and end Function: ";
for (auto i = a.begin(); i != a.end(); ++i)
cout << *i << " ";
//Printing the Output of vector ‘a’ using iterators cbegin() and cend()
cout << "\nOutput of cbegin and cend Function: ";
for (auto i = a.cbegin(); i != a.cend(); ++i)
cout << *i << " ";
//Printing the output of vector ‘a’ using iterators rbegin() and rend()
cout << "\nOutput of rbegin and rend Function: ";
for (auto ir = a.rbegin(); ir != a.rend(); ++ir)
cout << *ir << " ";
//Printing the output of vector ‘a’ using iterators crbegin() and crend()
cout << "\nOutput of crbegin and crend Function: ";
for (auto ir = a.crbegin(); ir != a.crend(); ++ir)
cout << *ir << " ";
return 0;
}
Output:
Capacity:
- size() – It returns the number of elements currently present in the vector.
- max_size() – It returns the maximum number of elements that a vector can hold.
- capacity() – It returns the storage capacity currently allocated to the vector.
- resize(n) – It resizes the container to store ‘n’ elements.
- empty() – It returns whether the container is empty or not.
Example Code for visualizing the use of capacity functions:
//C++ program to demonstrate working of capacity function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//Declaring vector ‘a’ of integer type
vector<int> a;
//Initializing vector ‘a’ with values from 1 to 5
for (int i = 1; i <= 5; i++)
a.push_back(i);
//Printing size of the vector ‘a’
cout << "Size : " << a.size();
//Printing the Capacity of the vector ‘a’
cout << "\nCapacity : " << a.capacity();
//Printing the maximum size of the vector ‘a’
cout << "\nMax_Size : " << a.max_size();
// resizing the vector ‘a’ to size 4
a.resize(4);
// printing the vector ‘a’ size after resize() function
cout << "\nSize : " << a.size();
// checks if the vector is empty or not
if (a.empty() == false)
cout << "\nVector is not empty";
else
cout << "\nVector is empty";
return 0;
}
Output:
Modifiers:
- assign() – It assigns a new value to the existing elements of the vector.
- push_back() – It pushes the element from back in the vector.
- pop_back() – It removes elements from the back of the vector.
- insert() – It inserts an element before a specified element in the vector.
- erase() – It is used to remove elements from a specified element or a range in the vector.
- swap() – It is used to swap the contents of two vectors of the same datatype. The sizes of vectors may differ.
- clear() – It is used to remove all the elements from the vector.
Example code to Visualize the Modifiers Function in vector:
//C++ code to visualize the Modifiers function in vectors
#include <bits/stdc++.h>
#include <vector>
using namespace std;
int main()
{
// Declaring Vector ‘a’ of integer type
vector<int> a;
// filling vector ‘a’ with 7 in repetition of 4 times
a.assign(4, 7);
//Printing the vector ‘a’ contents
cout << "The vector contains: ";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
// inserting 10 to the last position of vector ‘a’
a.push_back(10);
int n = a.size();
cout << "\nThe last element is: " << a[n - 1];
// removing the last element from vector ‘a’
a.pop_back();
// printing the vector ‘a’ contents
cout << "\nThe vector contains: ";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
// inserting 3 at the beginning of vector ‘a’
a.insert(a.begin(), 3);
//Printing the first element of vector ‘a’
cout << "\nThe first element is: " << a[0];
// removing the first element
a.erase(a.begin());
//Printing the new first element of vector ‘a’
cout << "\nThe first element is: " << a[0];
// erasing the vector
a.clear();
//printing the vector ‘a’ after erasing it
cout << "\nVector size after erase(): " << a.size();
// Creating two vectors ‘a1’ and ‘a2’ of integer type
vector<int> a1, a2;
//Pushing values in vector ‘a1’ and ‘a2’
a1.push_back(3);
a1.push_back(4);
a2.push_back(5);
a2.push_back(6);
//printing vector ‘a1’
cout << "\n\nVector 1 is: ";
for (int i = 0; i < a1.size(); i++)
cout << a1[i] << " ";
//printing vector ‘a2’
cout << "\nVector 2 is: ";
for (int i = 0; i < a2.size(); i++)
cout << a2[i] << " ";
// Swaping vectors ‘a1’ and ‘a2’
a1.swap(a2);
//Printing vector ‘a1’ after swapping with ‘a2’
cout << "\nAfter Swap \nVector 1 is: ";
for (int i = 0; i < a1.size(); i++)
cout << a1[i] << " ";
//printing vector ‘a2’ after swapping with ‘a1’
cout << "\nVector 2 is: ";
for (int i = 0; i < a2.size(); i++)
cout << a2[i] << " ";
return 0;
}
Output:
Element access:
- reference_operator[g]: It returns a reference to the ‘g’ element in the vetor.
- at(g): It returns a reference to the element at position ‘g’ in the vector.
- front(): It returns a reference to the first element in the vector.
- back(): It returns a reference to the last element in the vector.
- data(): It returns a direct pointer to the memory array which is used internally by the vector to store its owned elements.
Example code to visualize the Element access function in C++:
#include <bits/stdc++.h>
using namespace std;
int main()
{
//Declaring vector ‘a’ of integer type
vector<int> a;
//pushing values fn vector ‘a’ from 10 to 100
for (int i = 1; i <= 10; i++)
a.push_back(i * 10);
//Using reference operator to print vector ‘a’ third element
cout << "\nReference operator [g] : a[2] = " << a[2];
//printing element at index 4 of the vector ‘a’
cout << "\nat : a.at(4) = " << a.at(4);
//printing the front element of vector ‘a’
cout << "\nfront() : a.front() = " << a.front();
//printing the back element of vector ‘a’
cout << "\nback() : a.back() = " << a.back();
// pointer to the first element
int* pos = a.data();
//printing the first element of vector using pointer ‘pos’
cout << "\nThe first element is " << *pos;
return 0;
}
Output:
Allocators Function in Vector C++
- An allocator is an object that dynamically allocates and deallocates memory.
- In C++ vectors, there is only one function which can be used as an allocator. This function is called the get_allocator() function. We basically use the get_allocator() to allocate chunks of memory which in return a copy of the allocator object associated with the vector.
When to use Vectors?
We can use Vectors in the following circumstances:
It is advisable to use vectors when data are consistently changing.
If the size of data is unknown then it is advisable to use vectors.
It is advisable to use vectors when elements are not predefined.
Compared to arrays there are more ways to copy vectors.
Vectors and Array in C++
- Vector is a sequential container.
- Vector is not index based.
- Array is a fixed-size sequential collection of elements of the same type.
- Array is index based.
- Vectors are dynamic in nature.
- Once the array is initialized it’s size can’t be changed.
- Vector occupies more memory as compared to array.
- Array is memory efficient data structure.
- Accessing time in vectors is more.
- Array elements are arranged in contiguous memory allocation so it accesses elements in constant time.
- Vectors can be only declared in C++.
- Arrays can be declared in any programming language like C, Java, Python, etc.
Vector of Vectors in C++ STL
- Vector of Vectors is a two-dimensional vector with a variable number of rows where each row is considered as a vector.
- Each index of vector stores a vector in it. It can be accessed or traversed using iterators.
- Basically, it can be considered as the array of vectors with dynamic properties.
- Syntax:
- vector<vector<data_type>> vector_name;
Example code to visualize Vector of Vectors in C++:
//C++ program to visualize Vector of Vectors
#include <iostream>
#include <vector>
using namespace std;
// Defining the rows and columns of
// vector of vectors
#define row 3
#define col 3
int main()
{
// Initializing the vector of vectors
vector<vector<int> > a;
// Elements to insert in column
int num = 10;
// Inserting elements into vector
for (int i = 0; i < row; i++) {
// Vector to store column elements
vector<int> a1;
//pushing values in vector ‘a1’
for (int j = 0; j < col; j++) {
a1.push_back(num);
num += 5;
}
// for creating a 2D vector ‘a’ pushing 1D vector ‘a1’ into it
a.push_back(a1);
}
// Displaying the 2D vector ‘a’
cout<<"2D vector contains:"<<"\n";
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < a[i].size(); j++)
cout << a[i][j] << " ";
cout << endl;
}
//Deleting in 2D vector ‘a’
a[2].pop_back();
a[1].pop_back();
cout<<"2D vector traversal after deletion:"<<"\n";
//Traversing in 2D vector ‘a’ using iterator after deletion
for (int i = 0; i < a.size(); i++) {
for (
auto it = a[i].begin();
it != a[i].end(); it++)
cout << *it << " ";
cout << endl;
}
return 0;
}
Output:
Advantages of Vectors
- It is dynamic in nature.
- Elements can be inserted, deleted easily.
- Multiple objects can be stored.
- It is very easy to copy vectors from one to another by just using assignment operator.
Disadvantages of Vectors
- Memory consumption is more.
- It is not indexed.
- It doesn’t use contiguous memory.
Advantages of Arrays
- It supports random access to it’s members.
- It is more appropriate in storing a fixed number of elements.
- Uses contiguous memory.
- It is indexed.
- It is easy to sort in arrays.
Disadvantages of Arrays
- Dynamic creation of arrays is not possible.
- It cannot store multiple data types.
- Deletion of elements is not easy.
Summary
As we have learned about C++ vectors, it is clear that it is 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 in vectors as well as manage computer memory in an efficient manner.We can now understand where to apply vectors and where to apply arrays in a program.Vectors are an important concept for every C++ professional.
With this, we come to the end of this article on Vectors in C++. I hope you got an idea of how to use and where to use vectors in C++ programs. I hope you all got an idea of how arrays differ from vectors.