Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/rotate"

From cppreference.com
< cpp‎ | algorithm
m (Text replace - "<!-- ======== --> " to "")
(+more of my favorite examples)
Line 38: Line 38:
 
===Example===
 
===Example===
 
{{example cpp
 
{{example cpp
  |
+
  | The following is an implementation of insertion sort in C++
  | code=
+
  | code=#include <random>
 +
#include <vector>
 +
#include <iostream>
 +
#include <algorithm>
 +
#include <functional>
 +
#include <iterator>
  
| output=
+
template<typename Iter>
 +
void insertion_sort(Iter beg, Iter end)
 +
{
 +
    for (Iter i = beg; i != end; ++i)
 +
        std::rotate(std::upper_bound(beg, i, *i), i, i+1);
 +
}
  
 +
int main()
 +
{
 +
    std::random_device rd;
 +
    std::mt19937 gen(rd());
 +
    std::uniform_int_distribution<> dist(-10, 10);
 +
    std::vector<int> v;
 +
    generate_n(back_inserter(v), 20, bind(dist, gen));
 +
 +
    std::cout << "Before sort: ";
 +
    copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
 +
 +
    insertion_sort(v.begin(), v.end());
 +
 +
    std::cout << "\nAfter sort: ";
 +
    copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
 +
    std::cout << '\n';
 +
}
 +
| output=Before sort: 2 4 -1 2 0 -8 -7 -9 0 10 7 7 -5 -1 7 -5 -1 -7 -7 1
 +
After sort: -9 -8 -7 -7 -7 -5 -5 -1 -1 -1 0 0 1 2 2 4 7 7 7 10
 
}}
 
}}
  

Revision as of 12:44, 17 August 2011

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 ForwardIterator >
void rotate( ForwardIterator first, ForwardIterator n_first, ForwardIterator last );
</td>

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

Moves the elements in the range [first, last) in such a way, that the element n_first becomes the first element of the new range and n_first - 1 becomes the last element.

Contents

Parameters

first, last - the range of elements to rotate
n_first - the element to move to the beginning of the new range

Return value

Equivalent function

Template:eq fun cpp

Example

Template:example cpp

Complexity

linear in the distance between first and last

See also

Template:cpp/algorithm/dcl list rotate copy