Understanding Reverse Vector in C++

Understanding Reverse Vector in C++

4 mins read2.3K Views Comment
Updated on Feb 9, 2023 16:48 IST

Here you will understand how to reverse vector in C++ programming language. We have explained this concept with the help of its methods and examples. Let’s dive in.

2023_01_Reversing-a-Vector-in-C-1.jpg

Vectors are a powerful and versatile data structure that is commonly used in C++ programming. They are easy to use and can be very useful for storing and manipulating large amounts of data. In this article, we will learn how to reverse a vector in C++ through different methods. So, without further ado, let’s get started!

Explore- C++ Online Courses & Certifications

We will be covering the following sections:

Must read: What is Programming? All You Need To Know

What are Vectors in C++?

Vectors are a powerful data structure in C++ that can be used to store and manipulate data arrays. They are part of the Standard Template Library (STL) and are a dynamic array, meaning they can grow or shrink in size as needed.

A vector is declared using the keyword vector followed by the data type that the vector will store in angular brackets <>.

For example, to create a vector of integers, you would use the following syntax:

vector<int> myVector;

You can also initialize a vector with a set of values by passing in a list of elements to the constructor. For example:

 
vector<int> myVector {1, 2, 3, 4, 5};
Copy code

In C++, a vector is an array that can change its size automatically. The elements within a vector are stored together in memory. We use random access iterators to access or move through the elements in a vector. In addition, before we explore the various methods of vectors, let’s remind ourselves of the iterators vector::begin() and vector::end().

The function begin() returns an iterator that references the first element in the vector, while end() returns an iterator that points to the position after the last element in the vector.

When reversed, the vector would appear as follows:

It’s important to understand that when you reverse a vector, the positions of the iterators returned by begin() and end() remain the same. Only the values at the positions to which the iterators point are exchanged.

Explore popular Programming Courses

There are three easy methods for reversing a 1D vector. Let’s look at each of them:

Methods to Reverse a Vector

Using C++ vector STL function std::reverse()

A C++ vector can be reversed with the help of reverse() function provided in STL.

The std::reverse() function can be used to reverse the order of elements within a range [first,last). It takes two parameters, an iterator pointing to the first element in the range and an iterator pointing to the last element in the range. This function uses the std::iter_swap method to swap elements from both range ends.

Check out: Function Overloading in C++

Let’s take a look at an example:

 
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v={2,3,4,6,7,8};
cout<<"Original Vector: \n";
for(auto iter = v.begin(); iter < v.end(); iter++)
{
cout << *iter << " ";
}
cout <<"\n";
//std::reverse() function of STL
reverse(v.begin(),v.end());
cout<<"Reversed Vector:\n";
for (auto iter = v.begin(); iter < v.end(); iter++)
{
cout << *iter<< " ";
}
return 0;
}
Copy code

Output:

Time and Space Complexity

The time complexity of this function is O((last-first)/2), where first and last define the range of elements to be reversed. Therefore, reversing an entire vector using std::reverse() has a time complexity of O(n).

By Swapping the Elements of the Vector

A C++ vector can be reversed by traversing through it and swapping the elements within the range of v.begin() and v.end().

Let’s take a look at an example:

 
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v = { 7, 2, 9, 4, 6 };
cout<<"Original Vector: \n";
for(auto iter = v.begin(); iter < v.end(); iter++)
{
cout << *iter << " ";
}
cout <<"\n";
// swapping
for (auto first = v.begin(),last=v.end()-1; first<last; first++,last--) {
swap(*first, *last);
}
cout<<"Reversed Vector:\n";
for (auto iter = v.begin(); iter < v.end(); iter++)
{
cout << *iter<< " ";
}
return 0;
}
Copy code

Output:

Time and Space Complexity

The time complexity of reversing a vector using iterators is O((last-first)/2) which is equal to O(n). In terms of space complexity, we do not use any additional space; it is O(1).

Classes and Objects in C++
Classes and Objects in C++
If you are a student then you must have got this question in the exam or practical viva and if you are a job seeker then you must have faced...read more
New and Delete Operators in C++
New and Delete Operators in C++
The new operator is used to dynamically allocate memory on the heap for an object or an array of objects. And delete operator is used to deallocate the memory. This...read more
Exception handling in C++
Exception handling in C++
Exception handling in C++ provides a way to deal with unexpected situations such as run-time errors. In this we have covered Exception handling in C++with programming explanation with code explanation.In...read more

By Using Reverse Iterators

C++ vectors have reverse iterators, vector::rbegin() and vector::rend().

rbegin() returns a reverse iterator that points to the last element in the vector, and rend() returns a reverse iterator that points to the position before the first element in the vector.

We can create a new vector using the range constructor with reverse iterators as parameters to reverse a vector. This new vector will contain the elements of the original vector in reverse order.

We can then replace the original vector with the reversed vector by using vector::swap as v.swap(v2), std::swap as swap(v,v2), or simply by assigning v=v2.

Let’s take a look at an example:

 
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v={6,7,2,3,8};
cout<<"Original Vector: \n";
for(auto iter = v.begin(); iter < v.end(); iter++) {
cout << *iter << " ";
}
cout <<"\n";
vector<int> v2 (v.rbegin(),v.rend());
v.swap(v2);
cout<<"Reversed Vector:\n";
for(auto iter = v.begin(); iter < v.end(); iter++) {
cout << *iter << " ";
}
return 0;
}
Copy code

Output:

Time and Space Complexity

Swapping two vectors is a very efficient operation as it only requires swapping the memory addresses of the two vectors, making it a constant time complexity of O(1). However, creating a new vector and swapping it with the original vector requires extra memory space, which results in a space complexity of O(n).

Also explore: Top C++ Interview Questions and Answers for 2023

Endnotes

In conclusion, vectors are a powerful and versatile data structure in C++ that we can use to store and manipulate data arrays. This article was helpful for you in understanding how to reverse a 1D vector in C++. If you want to learn more about C++ and solidify your basics, you can explore our articles on C++.

Contributed By: Prerna Singh

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio