template<class BidirIt, class OutputIt>
OutputIt reverse_copy(BidirIt first, BidirIt last, OutputIt d_first);
Parameters
Parameter
Description
first, last
Required. The source range.
d_first
Required. Where the reversed copy starts.
Return Value
Return Value
Description
Iterator
Points just after the last element written in the destination.
C++ Examples
Example 1 — Keep the original
Reverse a vector into a new one.
C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> src = {1, 2, 3};
std::vector<int> out;
std::reverse_copy(src.begin(), src.end(), std::back_inserter(out));
std::cout << "src: ";
for (int x : src) std::cout << x << ' ';
std::cout << '\n';
std::cout << "out: ";
for (int x : out) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
Output
src: 1 2 3
out: 3 2 1
How It Works
reverse_copy() reads the source from the back.
std::back_inserter appends each element to out.
The source keeps its original order.
Example 2 — Palindrome check
A word is a palindrome if it reads the same backward.
C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main() {
std::string s = "madam";
std::string rev;
std::reverse_copy(s.begin(), s.end(), std::back_inserter(rev));
std::cout << s << (rev == s ? " is a palindrome" : " is not a palindrome") << '\n';
return 0;
}
Output
madam is a palindrome
How It Works
The reversed text of madam is built in rev.
Comparing rev == s checks whether both strings match.
They match, so the first message prints.
Example 3 — Reverse part of an array
Copy a reversed slice into a smaller array.
C++
#include <algorithm>
#include <iostream>
int main() {
int a[] = {1, 2, 3, 4, 5};
int b[3];
std::reverse_copy(a + 1, a + 4, b);
for (int x : b) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
Output
4 3 2
How It Works
a + 1 and a + 4 select 2, 3 and 4.
They are written into b in reverse order.
The elements 1 and 5 are outside the range, so they are ignored.
Frequently Asked Questions
In C++, std::reverse_copy() copies a range into a destination in reverse order. Include <algorithm> to use it.
Include <algorithm>. It has been part of C++ since C++98, so every modern compiler supports it.
It returns an iterator to the position after the last element written in the destination.
reverse() changes the range in place. reverse_copy() writes the reversed elements to another place and keeps the source.