4

I want to move first element of vector to the end of vector.

v = {1,2,3,4} after this should be like this

v= {2,3,4,1}

my compiler version is gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5.1)

I know in Vc11 we can use std::move to move element. but how can I do this in above version of compiler?

Muhammad Zaighum
  • 560
  • 4
  • 21

3 Answers3

3

As noted in the comments, std::rotate is one possible way:

std::rotate( v.begin(), v.begin() + 1, v.end() );
Columbo
  • 60,038
  • 8
  • 155
  • 203
3

There's a std::rotate algorithm in the standard library:

std::rotate(ObjectToRotate.begin(),
            ObjectToRotate.end()-1, // this will be the new first element
            ObjectToRotate.end());
  • For me this swaps the first and last elements instead of just moving the first item to the back. – Alex Oct 05 '21 at 20:50
1

You should consider using std::rotate or if you want it the ugly way: Create a function that safes the last and the first element in local variables, create a new local vector, but the last element as first in the vector. Put begin+1 till end-1 in the vector and then the first element.

user3718058
  • 303
  • 1
  • 3
  • 11