The difference is that copy
returns an iterator to the pass-the-end element while copy_backward
returns an iterator to the first element.
They are not equivalent in that sense.
- The signatures of course differ.
copy
is ok with InputIterator
s and OutputIterator
. Whilst copy_backward
expects BidirectionalIterator
s.
- The effect on the container (when used correctly) is the same, but the returned iterators are of different types and point to different elements.
Example:
This works because vector
can use RandomAccessIterator
which does support the properties expected by InputIterator
, OutputIterator
and BidirectionalIterator
.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void printer(int i) {
cout << i << ", ";
}
int main() {
int mynumbers[] = {3, 9, 0, 2, 1, 4, 5};
vector<int> v1(mynumbers, mynumbers + 7);
vector<int>::iterator it = copy_backward(mynumbers, mynumbers + 7, v1.end());
for_each(v1.begin(), v1.end(), printer);
cout << endl << "Returned element: " << *it;
cout << endl;
vector<int>::reverse_iterator rit = copy(mynumbers, mynumbers + 7, v1.rbegin());
for_each(v1.begin(), v1.end(), printer);
cout << endl << "Before the first element (reverse end)? " << (rit == v1.rend());
rit--; // go to first element, because it is a reverse iterator
cout << endl << "Returned element: " << *rit;
return 0;
}
Result:
3, 9, 0, 2, 1, 4, 5,
Returned element: 3
5, 4, 1, 2, 0, 9, 3,
Before the first element (reverse end)? 1
Returned element: 5
If you'd use a container that does not support BidirectionalIterator
then you risk trouble (e.g. if you'd try to copy backward a forward_list
because it uses a ForwardIterator
, which is does not support operations provided by a BidirectionalIterator
).
Also in this case copying with reverse iterator on forward_list
is also not possible, because it does not support reverse iterators.
Basically, you need to make sure the container's iterators are supported and choose according to which end of the container you'd like to have returned. Otherwise the effect is the same.
reverse_iterator
requires the iterator type to be properly tagged whereascopy_backward
is implemented as a simple loop. Obviously that's not guaranteed, though. As far as the standard is concerned, all iterators must be tagged.T*
is tagged as a random-access iterator, since there is a guaranteed partial specializationtemplate<class T> struct iterator_traits<T*>;
.