std::reverse() in C++
reverse() is a predefined function in header file algorithm. It is defined as a template in the above mentioned header file. It reverses the order of the elements in the range [first, last) of any container.
Note: The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
Syntax:
void reverse(BidirectionalIterator first, BidirectionalIterator last) BidirectionalIterator is an iterator that can be used to access any elements of a container in both forward and backward direction.
Examples:
Input : 10 11 12 13 14 15 16 17 Output :10 11 12 13 14 17 16 15 Explanation: reverse(v.begin() + 5, v.begin() + 8); In the above function, input we have applied reverse() on the vector from index 5 to index 7. Therefore when we display the vector we get reverse order from index 5 to index 7.
// CPP program to illustrate // std::reverse() function of STL #include<iostream> #include<algorithm> #include<vector> using namespace std; int main() { vector <int> v ; // Inserting elements in vector for (int i = 0; i < 8; i++) v.push_back(i+10); cout << "Reverse only from index 5 to 7 in array:\n"; // Reversing elements from index 5 to index 7 reverse(v.begin() + 5, v.begin() + 8); // Displaying elements of vector vector <int> :: iterator it; for (it = v.begin(); it != v.end(); it++) cout << (*it) << " "; // Reversing directly from beginning to end cout << "\nReverse full array:\n"; int a[] = {4, 5, 6, 7}; std::reverse(std::begin(a), std::end(a)); // Print the array std::cout << a[0] << a[1] << a[2] << a[3] << '\n'; return 0; } |
Output:
Reverse only from index 5 to 7 in array: 10 11 12 13 14 17 16 15 Reverse full array: 7654
This article is contributed by Hardik Gaur. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Find the Deepest Node in a Binary Tree Using Queue STL - SET 2
- C++ program to compare two Strings using Operator Overloading
- not1 and not2 function templates in C++ STL with Examples
- Go vs C++
- Trie Data Structure using smart pointer and OOP in C++
- Modular Exponentiation of Complex Numbers
- std::hash class in C++ STL
- History of C++
- What are Forward declarations in C++
- __builtin_inf() functions of GCC compiler
- Structures in C++
- Variables in C++
- Implementing Forward Iterator in BST
- Count substrings that contain all vowels | SET 2
- Machine Learning in C++



