std::rotate_copy() function with example in C++ STL

C++ STL | std::rotate_copy() function: Here, we are going to learn about the rotate_copy() function of algorithm header in C++ STL with example.
Submitted by IncludeHelp, on May 26, 2019

C++ STL std::rotate_copy() function

rotate_copy() function is a library function of algorithm header, it is used to rotate left the elements of a sequence within a given range and copy the rotating elements to another sequence, it accepts the range (start, end) of the input sequence, a middle point, and an iterator pointing to start element of result sequence. It rotates the elements in such a way that the element pointed by the middle iterator becomes the new first element.

Note: To use rotate_copy() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.

Syntax of std::rotate_copy() function

    std::rotate_copy(
        iterator start,  
        iterator middle, 
        iterator end, 
        iterator start_result);

Parameter(s):

  • iterator start – an iterator pointing to the first element of the sequence.
  • iterator middle – an iterator pointing to the middle or any other elements from where we want to start the rotation.
  • iterator end – an iterator pointing to the last element of the sequence.
  • iterator start_result – an iterator pointing to the first element in result sequence.

Return value: void – it returns noting.

Example:

    Input:
    //an array (source)
    int arr[] = { 10, 20, 30, 40, 50 };
    //vector
    vector<int> v(5);
    
    //rotating and copy array elements to the vector
    rotate_copy(arr + 0, arr + 2, arr + 5, v.begin());
        
    Output:
    vector elements: 30 40 50 10 20

C++ STL program to demonstrate use of std::rotate_copy() function

In this program, we have an array and a vector; we are rotating its elements from 2nd index and copying into the vector.

//C++ STL program to demonstrate use of
//std::rotate_copy() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

//main code
int main()
{
    //an array (source)
    int arr[] = { 10, 20, 30, 40, 50 };

    //vector
    vector<int> v(5);

    //printing array and vector elements
    cout << "array elements..." << endl;
    for (int x : arr)
        cout << x << " ";
    cout << endl;

    cout << "vector elements begfore rotating..." << endl;
    for (int x : v)
        cout << x << " ";
    cout << endl;

    //rotating and copy array elements to the vector
    rotate_copy(arr + 0, arr + 2, arr + 5, v.begin());

    cout << "vector elements after rotating..." << endl;
    for (int x : v)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

array elements...
10 20 30 40 50
vector elements begfore rotating...
0 0 0 0 0
vector elements after rotating...
30 40 50 10 20

Reference: C++ std::rotate_copy()




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.