• Articles
• Tutorials
• Interview Questions
• Webinars

How to Reverse Vector in C++: Complete Guide

In C++, a vector is like a dynamic array. It lets you store a collection of items, and the cool part is that you reverse it when required. In this blog, we will discuss four techniques of reversing vectors in C++ with examples such as reverse function, swapping elements, and more.

Check out our YouTube video on C programming language for absolute beginners!

Reversing a Vector in C++

A vector in C++ is a dynamic array that can resize itself automatically when elements are added or removed. Reversing a vector in C++ means changing the order of its elements so that the last element becomes the first, the second-to-last becomes the second, and so on. Essentially, the vector is flipped in the opposite direction.

For example, if the Initial Vector is {1, 2, 3, 4, 5} then the Reversed Vector: is {5, 4, 3, 2, 1}

Do you want to jumpstart your career in computer programming? Enroll in our C Programming Course and gain the skills to succeed!

Methods to Reverse a Vector

We can reverse a vector in C++ in four major ways. Let’s understand how we can reverse a vector using these methods:

By using reverse() Function

The reverse() function from the <algorithm> header reverses the elements in a given range. It takes two objects that allow you to traverse through the elements indicating the range (begin(), end()) of the vector. These objects are called iterators. It reverses the order of elements within this range, modifying the original vector. The function efficiently swaps elements from the start and end of the range until they meet in the middle.

```#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
cout<<"Original Vector : 1 2 3 4 5 "<<endl;
// Reversing the vector using reverse() function
std::reverse(numbers.begin(), numbers.end());
cout<<"Vector with reversed elements : ";
// Displaying the reversed vector
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}```

Do you want to learn C programming in depth? Visit our C Tutorial.

By Swapping the Elements of the Vector

In this method, we manually swap elements from the start to the end of the vector. It involves setting two indices(location of elements in the vector), one at the start (0) and one at the end (size() – 1) of the vector. Then we will systematically access and process each element along with swapping them at these indices, and move toward the center of the vector. This process continues until the two indices meet or cross each other.

```#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
cout<<"Original Vector : 1 2 3 4 5 "<<endl;
int start = 0;
int end = numbers.size() - 1;
while (start < end) {
std::swap(numbers[start], numbers[end]);
start++;
end--;
}
cout<<"Vector with reversed elements : ";
// Displaying the reversed vector

for (int num : numbers) {

std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}```

Get ready for high-paying programming jobs with these Top C & Data Structure Interview Questions and Answers!

By Using Reverse Iterators

In C++, a reverse iterator is an iterator that allows you to traverse a vector in the reverse order. In this method, the reverse iterators rbegin() and rend() are used to reverse the vector. rbegin() points to the last element of the vector, while rend() points to a position before the first element (i.e., one position before begin()). During this reversal traversal, each element from the end of the vector is copied to the beginning. This way, we can construct a new vector in reverse order.

```#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::vector<int> reversed;
cout<<"Original Vector : 1 2 3 4 5 "<<endl;
// Reversing the vector using reverse iterators
for (auto it = numbers.rbegin(); it != numbers.rend(); ++it) {
reversed.push_back(*it);
}
cout<<"Vector with reversed elements : ";
// Displaying the reversed vector
for (int num : reversed) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}```

By Using transform() Function

We can reverse a vector using the transform() function from the <algorithm> header, along with reverse iterators. The <algorithm> header in C++ provides a collection of functions that facilitate operations on sequences, such as searching, sorting, and manipulating elements within a range.

transform() applies a specified operation to each input sequence element and stores the result in an output container. It uses reverse iterators (numbers.rbegin() and numbers.rend()) to traverse the input vector in reverse order. It effectively copies each element from the original vector into the new reversed vector.

```#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::vector<int> reversed;
cout<<"Original Vector : 1 2 3 4 5 "<<endl;
// Reversing the vector using transform() function with reverse iterators
std::transform(numbers.rbegin(), numbers.rend(), std::back_inserter(reversed), [](int i) { return i; });
cout<<"Vector with reversed elements : ";
// Displaying the reversed vector
for (int num : reversed) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}```

Conclusion

Reversing a vector in C++ can be achieved through the methods explained above. Utilizing the `reverse()` function efficiently reverses elements in place, while manual swapping and reverse iterators provide alternate approaches by copying the elements. Understanding these methods empowers developers to choose the most suitable technique based on specific needs, whether prioritizing readability, efficiency, or modifying the original vector.

You can also make your C++ code more organized with concepts like Inheritance that allow sharing and customizing code using Object Oriented Programming(OOP). This helps in building flexible and reusable programs. Moreover, Exception Handling ensures that errors are managed smoothly, making the program more reliable.

Don’t miss out on the latest programming trends and advancements; be part of Intellipaat’s Community today!

Course Schedule

Name Date Details
Python Course 22 Jun 2024(Sat-Sun) Weekend Batch
View Details
Python Course 29 Jun 2024(Sat-Sun) Weekend Batch
View Details
Python Course 06 Jul 2024(Sat-Sun) Weekend Batch
View Details