Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/reverse copy"

From cppreference.com
< cpp‎ | algorithm
(Example: return 0 is implicit for main() in C++ -> not needed)
(Possible implementation: fmt)
Line 23: Line 23:
 
===Possible implementation===
 
===Possible implementation===
 
{{eq fun cpp | 1=
 
{{eq fun cpp | 1=
template< class BidirectionalIterator, class OutputIterator >
+
template<class BidirectionalIterator, class OutputIterator>
    OutputIterator reverse_copy( BidirectionalIterator first,
+
OutputIterator reverse_copy(BidirectionalIterator first,
                                BidirectionalIterator last,
+
                            BidirectionalIterator last,
                                OutputIterator d_first )
+
                            OutputIterator d_first)
    {
+
{
        while (first != last) {
+
    while (first != last) {
            *(d_first++) = *(--last);
+
        *(d_first++) = *(--last);
        }
+
        return d_first;
+
 
     }
 
     }
 +
    return d_first;
 +
}
 
}}
 
}}
  

Revision as of 12:56, 13 May 2012

Template:cpp/algorithm/sidebar Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <algorithm>
</td>

<td></td> <td></td> </tr> <tr class="t-dcl ">

<td class="t-dcl-nopad">
template< class BidirectionalIterator, class OutputIterator >
OutputIterator reverse_copy( BidirectionalIterator first, BidirectionalIterator last, OutputIterator d_first );
</td>

<td class="t-dcl-nopad"> </td> <td class="t-dcl-nopad"> </td> </tr> Template:ddcl list end

Copies the elements from the range [first, last), to another range beginning at d_first in such a way, that the elements in the new range are in reverse order.

Contents

Parameters

first, last - the range of elements to copy
d_first - the beginning of the destination range

Return value

output iterator to the element past the last element copied.

Possible implementation

Template:eq fun cpp

Example

#include <vector>
#include <iostream>
#include <algorithm>
 
#include <vector>
#include <iostream>
#include <algorithm>
 
int main(int argc, char** argv)
{
    std::vector<int> v({1,2,3});
    std::for_each(std::begin(v), std::end(v),
                  [&](int value){ std::cout << value << " "; });
    std::cout << std::endl;
 
    std::vector<int> destiny(3);
    std::reverse_copy(std::begin(v), std::end(v), std::begin(destiny));
    std::for_each(std::begin(destiny), std::end(destiny),
                  [&](int value){ std::cout << value << " "; });
    std::cout << std::endl;
}

Output:

1 2 3 
3 2 1

Complexity

linear in the distance between first and last

See also

Template:cpp/algorithm/dcl list reverse