Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Vector in C++
3.
Need for Vectors
4.
How to create vectors in C++?
5.
Syntax:
6.
Difference Between Vector and Array
7.
Declaring and Initializing a vector
7.1.
Method 1
7.2.
Method 2
7.3.
C++
8.
Basic Operations 
8.1.
Add elements to a vector
8.2.
C++
8.3.
Access Elements of a vector
8.4.
C++
8.5.
Update vector element
8.6.
C++
8.7.
Delete elements from a vector
8.8.
C++
9.
Basic Vector Functions
9.1.
C++
10.
Vector Iterators
10.1.
C++
11.
Frequently Asked Questions
11.1.
Can we declare vectors of user-defined type?
11.2.
What is the difference between back() and pop_back() function?
11.3.
What is the difference between size() and capacity() function?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

Vectors in C++

Introduction

In programming languages like C++, we usually use arrays when we want to store homogeneous elements(elements of the same data-type). The main problem when working with arrays is that they are of a fixed size that must be specified beforehand, because of which, it becomes difficult to insert or delete elements from the array during compile time. Vectors are dynamic arrays that can resize when elements are inserted or deleted automatically at runtime. Like arrays, elements of vectors are placed at contiguous storage therefore, they can be accessed and traversed easily using iterators. Elements are added at the end in vectors that take differential time, whereas removing the last elements takes constant time.

Vectors in C++

In this article, We will discuss Vectors in C++ in detail.

What is a Vector in C++

In C++, the class template std::vector contains the vector container and its member functions. It is specified in <vector> header file. The member functions of the std::vector class provide various containers with a variety of features. Vectors are similar to dynamic arrays in that they can resize themselves dynamically when an element is added or removed, and their storage is handled automatically by the container.

Vector elements are stored in contiguous storage so that iterators can access and traverse them. Data is put at the end of vectors. Inserting at the end requires a variable amount of time because the array may need to be extended at times. As there is no scaling, removing last element requires only constant time. Inserting and erasing at the start or end of a line is linear in time.

Need for Vectors

  • Vectors are a resizable array-like data structure that allows for dynamic memory allocation
     
  • Vectors efficiently manage memory, automatically resizing when necessary and freeing memory when elements are deleted
     
  • Vectors may store pieces of any data type, making them adaptable and useful for a variety of data storage and manipulation tasks
     
  • Vectors provide a simple and consistent interface for adding, accessing, and removing items, making dynamic arrays easier to deal with for programmers

How to create vectors in C++?

In order to generate a vector in C++, you must first include the vector library.

This is accomplished by including the line #include <vector> at the top of your file. This line follows #include <iostream> and any other header files you've included in your program.

The #include <vector> library includes std::vector.

Example:

#include <iostream>
#include <vector>
int main() {
//without specifying the number of elements
//defines a vector named prices that stores floating point numbers
std::vector<double> prices;
}

Syntax:

The general syntax for constructing a vector is as follows:

std::vector<data_type> name (items);

 

In the above syntax the <data_type> refers to the type of data that you want to store in the vector. It can be any valid data type like string, integer, char, etc. The “name” field shows the name of the vector declared. The “items” field given in the brackets signifies the number of data items that you want to store inside the vector, but it is an optional part.

Difference Between Vector and Array

S.No Vector Array
1 Memory is allocated dynamically. Memoy is allocated statically.
2 Internally, the vector shifts all of the elements. After deletion, the user must explicitly relocate elements in the application.
3 Using push_back(), we can insert elements that are larger than the size of the vector. We cannot insert more elements than the array's size.
4 We can resize the vector using the member function even after initialization using vector::resize(new_size_of_vector); Once declared, the array cannot be resized.
5 Vectors provide iterators, which allow us to do many types of traversals. As arrays do not provide iterators, we must rely on loops for traversal.
6 We can update an element in a vector in the same way that we can update an array element by using the index and subscript operator []. We may also achieve this with iterators, as previously explained, and the vector::at(); function. We can use the index and subscript operator [] to update any entry in the array.
7 There are several methods for copying one vector to another::assign(); Only by iterating over the entire array and copying values to the second array of the same data type can we transfer one array to another.

Declaring and Initializing a vector

Vectors in C++ are available in vector.h header file. Once the header file is included, we can use and declare vectors anywhere in the program. 

Syntax

std::vector<T> vector_name || vector<T> vector_name;


<T> specifies the type of values stored in the vector. <T> can be of primitive (like int, char, float, etc.) as well as user-defined(like class, struct, etc.) data types.

Note: when declaring a vector, we do not specify the size of the vector because the size of a vector grows dynamically.

Vectors can be declared in the following ways:

Method 1

In this method, we initialize the vector by providing the values directly to the vector.
 

// Initializer list
vector<int> x={10,20,30,40,50};

// Uniform initialization
vector<int> x {10,20,30,40,50};


Method 2

In this method, we pass two parameters: the size of the vector and the value with which to initialize the vectors.
 

vector<int> v(5,1); -> vector<int> v={1,1,1,1,1};


Example

  • C++

C++

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

int main() {

 // METHOD - 1
 // initializer list
 vector<int> v1 = {1, 2, 3, 4, 5};
 // uniform initialization
 vector<int> v2{1, 2, 3, 4, 5};

 // METHOD - 2
 vector<int> v3(5, 1);

 cout << "Elements of Vector-1 = ";
 for (const int& i : v1) {
 cout << i << " ";
}

 cout << "\nElements of Vector-2 = ";
 for (const int& i : v2) {
 cout << i << " ";
}

 cout << "\nElements of Vector-3 = ";
 for (int i : v3) {
 cout << i << " ";
}

}


Output

Elements of Vector-1 = 1 2 3 4 5  
Elements of Vector-2 = 1 2 3 4 5  
Elements of Vector-3 = 1 1 1 1 1  

Basic Operations 

Add elements to a vector

Elements can be added at the end of a vector during run-time using the push_back() function.

Example

  • C++

C++

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

int main() {
vector<int> v {1, 2};

cout<<"Vector before adding elements : ";

for (const int& i : v) {
 cout << i << " ";
}

// add 3 then 4
v.push_back(3);
v.push_back(4);

cout << "\nVector after adding elements : ";

for (const int& i : v) {
 cout << i << " ";
}
}


Output

Vector before adding elements : 1 2  
Vector after adding elements : 1 2 3 4 


Access Elements of a vector

Elements of a vector can be accessed randomly using either the angular brackets as we do in arrays or the at() function to access the elements from a specified index.

Example

  • C++

C++

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

int main() {
 vector<int> v {10, 20, 30, 40, 50};

 cout<<"Vector elements : ";

 for (const int& i : v) {
 cout << i << " ";
}
 cout<<endl;
 cout<<"Element at 2 position : "<<v[2]<<endl;
 cout<<"Element at 3 position : "<<v.at(3)<<endl;
}


Output

Vector elements : 10 20 30 40 50  
Element at 2 position : 30
Element at 3 position : 40


Update vector element

Vector elements can be updated with the help of at() function by using the element’s index.

Example

  • C++

C++

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

int main() {
 vector<int> v {10, 20, 30, 40, 50};

 cout<<"Vector elements Before : ";
 for (const int& i : v) {
 cout << i << " ";
}
 cout<<endl;
 cout<<"Increment the value at position 2 "<<endl;
v.at(2)+=1;
 cout<<"Decrement the value at position 4 "<<endl;
v.at(4)-=1;

 cout<<"Vector elements After : ";
 for (const int& i : v) {
 cout << i << " ";
}
}


Output

Vector elements Before : 10 20 30 40 50  
Increment the value at position 2 
Decrement the value at position 4 
Vector elements After : 10 20 31 40 49  


Delete elements from a vector

Elements can be removed from the vector from the end using the pop_back() function.

Example

  • C++

C++

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

int main() {
 vector<int> v {10, 20, 30, 40, 50};

 cout<<"Vector elements Before : ";
 for (const int& i : v) {
 cout << i << " ";
}
 cout<<endl;

 // removing element at index 4
 cout<<"Removing the last element "<<endl;
v.pop_back();
 cout<<"Updated Vector elements : ";
 for (const int& i : v) {
 cout << i << " ";
}
 cout<<endl;

 // removing element at index 3
 cout<<"Removing the last element "<<endl;
v.pop_back();
 cout<<"Updated Vector elements : ";
 for (const int& i : v) {
 cout << i << " ";
}
}


Output

Vector elements Before : 10 20 30 40 50  
Removing the last element 
Updated Vector elements : 10 20 30 40  
Removing the last element 
Updated Vector elements : 10 20 30  

Basic Vector Functions

In C++, various vector functions are predefined in the vector.h header file, which can perform different operations on vectors.

size(): This function returns the number of elements in the vector.

clear(): This function is used to empty a vector by removing all the vector elements.

front(): This function returns the first element of the vector.

back(): This function returns the last element of the vector.

empty() : This function returns a boolean value, true if vector is empty else false.

capacity(): This function is used to check the overall size of a vector.
 

Example

  • C++

C++

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

int main() {
 vector<int> v {1, 2, 3, 4, 5};

 cout<<"Vector : ";
 for (const int& i : v) {
 cout << i << " ";
}
 cout<<endl;

cout<<"size of the vector is : "<<v.size()<<endl;
cout<<"The First element of the vector is : "<<v.front()<<endl;
cout<<"The last element of the vector is : "<<v.back()<<endl;

v.pop_back();// removing an element
cout<<"Removing an element from the vector"<<endl;
cout<<"Vector : ";
 for (const int& i : v) {
 cout << i << " ";
}
 cout<<endl;

cout<<"The capacity of vector is : "<<v.capacity()<<endl;

//clear the vector
v.clear();
cout<<"Remove all the elements of the vector"<<endl;

if(v.empty()){
 cout<<"vector is empty"<<endl;
}else{
 cout<<"vector is not empty"<<endl;
}
}


Output

Vector : 1 2 3 4 5  
size of the vector is : 5
The First element of the vector is : 1
The last element of the vector is : 5
Removing an element from the vector
Vector : 1 2 3 4  
The capacity of vector is : 5
Remove all the elements of the vector
vector is empty

Vector Iterators

begin() : The begin() function returns an iterator pointing to the first element of the vector.

end() : The end() function returns an iterator pointing to the last element of the vector.

rbegin(): The rbegin() function returns a reverse iterator pointing to the last element of the vector (reverse vector).

rend(): The rend() function returns a reverse iterator pointing to the first element of the vector (reverse vector).

cbegin() : The cbegin() function returns a constant iterator pointing to the first element of the vector.

cend(): The cend() function returns a constant iterator pointing to the last element of the vector.

crbegin(): The crbegin() function returns a constant reverse iterator pointing to the last element of the vector (reverse vector).

crend(): The crend() function returns a constant reverse iterator pointing to the first element of the vector (reverse vector).

Example

  • C++

C++

#include <iostream>
#include <vector>

using namespace std;

int main()
{
 vector<int> v;

 // inputting vector elements
 for (int i = 10; i <= 40; i=i+10)
v.push_back(i);

 cout << "Vector using begin() and end() : ";
 for (auto i = v.begin(); i != v.end(); ++i)
 cout << *i << " ";

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

 cout << "\nVector using rbegin() and rend() : ";
 for (auto ir = v.rbegin(); ir != v.rend(); ++ir)
 cout << *ir << " ";

 cout << "\nVector using crbegin() and crend() : ";
 for (auto ir = v.crbegin(); ir != v.crend(); ++ir)
 cout << *ir << " ";

 return 0;
}


Output

Vector using begin() and end() : 10 20 30 40 
Vector using cbegin() and cend() : 10 20 30 40 
Vector using rbegin() and rend() : 40 30 20 10 
Vector using crbegin() and crend() : 40 30 20 10 

Frequently Asked Questions

Can we declare vectors of user-defined type?

Yes, vectors can be created of any type, primitive and user-defined types like classes, structures, etc.

What is the difference between back() and pop_back() function?

The difference between the back() and pop_back() function is that back() function is used to return the last element of the vector, whereas the pop_back() function is used to remove the last element of the vector.

What is the difference between size() and capacity() function?

The difference between the size() and capacity() function is that the size() function returns the number of components in the vector, whereas the capacity() function returns the maximum number of elements the vector can hold.

Conclusion

In this article, we have extensively discussed about Vectors in C++, how can we declare them, and what all vector functions are available in C++ programming languages and their implementation in Visual Studio Code.

We hope that this blog has helped you enhance your knowledge regarding vectors in the C/C++ programming language and if you would like to learn more, check out the following articles -

 

To learn more about Data Structures and Algorithms, you can enroll in our DSA in C++ Course.
Do upvote our blog to help other ninjas grow. Happy Coding!”

Live masterclass