C++ <algorithm> - reverse_copy() Function
The C++ algorithm::reverse_copy function is used to copy all elements in the range [first, last) to the range starting at result in reverse order.
Syntax
template <class BidirectionalIterator, class OutputIterator> OutputIterator reverse_copy (BidirectionalIterator first, BidirectionalIterator last, OutputIterator result);
Parameters
first |
Specify initial position of the bidirectional iterator. The range used is [first,last). |
last |
Specify final position of the bidirectional iterator. The range used is [first,last). |
result |
Specify initial position of the output iterator where the result to be stored. |
Return Value
Returns an output iterator pointing to the element that follows the last element copied in result sequence.
Time Complexity
Linear i.e, Θ(n).
Example:
In the example below, the algorithm::reverse_copy function is used to copy all elements of an array to a vector in reverse order.
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main (){ int arr[] = {10, 11, 12, 13, 14, 15}; vector<int> vec(6); vector<int>::iterator it; //copy elements from array to vector in reverse order reverse_copy(arr, arr+6, vec.begin()); cout<<"arr contains:"; for(int i = 0; i < 6; ++i) cout<<" "<<arr[i]; cout<<"\nvec contains:"; for(it = vec.begin(); it != vec.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
arr contains: 10 11 12 13 14 15 vec contains: 15 14 13 12 11 10
❮ C++ <algorithm> Library