aman_49
aman_49

Reputation: 116

Rotate the complete array using rotate function

A array contains element 10,20,30,40,50 What i wanna rotate the complete array so as it will cout will stream elements 50,40,30,20,10

I want to solve this problem using rotate function

i tried to write rotate(arr,arr+4,arr+1);

  #include<iostream>
  #include<algorithm>
  using namespace std;
  int main()
  {
      int arr[]={10,20,30,40,50};

      rotate(arr,arr+4,arr+1);
      int i;

      for(i=0; i<5; ++i)
      {
       cout<<arr[i]<<"  ";
      }
   }

by running above program i getting output 50 10 20 30 40 which is wrong the actual output is 50 40 30 20 10

Upvotes: 2

Views: 167

Answers (3)

Amit G.
Amit G.

Reputation: 2674

std::rotate: "Rotates the order of the elements in the range (first,last), in such a way that the element pointed by middle becomes the new first element."

Your std::rotate middle points to "arr+4" i.e. the 5th element: 50.

enter image description here

You expect "50 40 30 20 10" i.e. to reverse the array; not to rotate it. So, you should use std::reverse:

#include <array>
#include <algorithm>
#include <iostream>

int main()
{
    std::array<int, 5> arr { 10,20,30,40,50 };

    std::reverse(arr.begin(), arr.end());

    for (auto i : arr)
        std::cout << i << "  ";

    return 0;
}

Upvotes: 1

Junhee Shin
Junhee Shin

Reputation: 758

This is not a good idea, but I tried to solve this with using rotate()...

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;
int main()
{
    vector<int> v{10,20,30,40,50};
    int i;

    for(i=0; i<5; ++i)
    {
       cout<<v[i]<<"  ";
    }
    cout << endl ;

     for(i=0; i<5; ++i)
     {
        rotate(v.rbegin(),v.rbegin()+1,v.rend());
        cout<<v[0]<<"  ";
     }
     cout << endl ;
}

g++ rotatev.cpp --std=c++11

./a.out
10  20  30  40  50  
50  40  30  20  10  

Upvotes: 0

Bob__
Bob__

Reputation: 12749

The issue is that you picked the wrong algorithm (quotes from https://en.cppreference.com/w/, emphasis mine):

Specifically, std::rotate swaps 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.

What you need is std::reverse(first, last), which

Reverses the order of the elements in the range [first, last) Behaves as if applying std::iter_swap to every pair of iterators first+i, (last-i) - 1 for each non-negative i < (last-first)/2

Upvotes: 3

Related Questions