Join the social network of Tech Nerds, increase skill rank, get work, manage projects...

• # Reverse in C++

• 0
• 1
• 0
• 0
• 0
• 0
• 0
• 0
• 238
Comment on it

If you want to reverse the order of elements in a given range, then you can use the reverse function defined in the STL algorithm.

Template for reverse

```template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last);
```

InputIterator first
InputIterator first for the initial position of the range which is included in the range.
InputIterator last
InputIterator last for the final position which it not included in the range.

A sample program using reverse

```#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
vector <int> v;
vector <int>:: iterator it;

// Pushing 11 random elements inside the vector
v.push_back(11);
v.push_back(10);
v.push_back(9);
v.push_back(8);
v.push_back(7);
v.push_back(6);
v.push_back(5);
v.push_back(4);
v.push_back(3);
v.push_back(2);
v.push_back(1);

// printing the elemnets inside the raange
cout <<"Elements inside the range. " << endl;
for ( it = v.begin(); it != v.end(); it++)
cout << *it << " ";
cout << endl;

//applying reverse function on the range
reverse(v.begin(),v.end());

// printing the elemnets inside the range
cout <<"Elements inside the range after reverse. " << endl;
for ( it = v.begin(); it != v.end(); it++)
cout << *it << " ";
cout << endl;

return 0;
}
```

Output of the above program

```Elements inside the range.
11 10 9 8 7 6 5 4 3 2 1
Elements inside the range after reverse.
1 2 3 4 5 6 7 8 9 10 11
```

Time complexity for reverse is linear in half the distance between the range.

## 0 Comment(s)

OR
OR
Register

OR
Fill out the form below and instructions to reset your password will be emailed to you:

• Hire
• Post Projects

### Post Projects

• All at 0 Cost ....
• Post Tech Job
• Select Best Bidder
• Track the Project
• Approve Work and Pay safely
• Browse Nerds
• Work
• Find Projects Find Projects
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
• Manage
• Company Company

### Manage Company

• All at 0 Cost ....
• Manage Company and Employee Profiles
• Company wide Employee Productivity Reports
• Knowledge Sharing and Collaboration Tools
• Get Sales Lead and Bid for Tech Projects
• Send Invoices and Receive Payment Safely
• Learn
• Nerd Digest Nerd Digest
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
• Tech Q & A Tech Q & A
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General