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?

8
  • 4
    You are looking for std::rotate. Commented Oct 13, 2014 at 18:00
  • 1
    Also, std::move does not move things in that sense. Anyway, there are good examples here: std::rotate. Commented Oct 13, 2014 at 18:02
  • Maybe a std::deque would be more appropriate of this. Commented Oct 13, 2014 at 18:07
  • Funnily enough, you can also call remove(v.begin(), v.end(), v.at(0)) if there are no duplicates. I wouldn't do that, but... funnily enough. :) Commented Oct 13, 2014 at 18:11
  • 1
    @MuhammadZaighum: Because deque has efficient pop_front()/push_front() besides the *_back() variants, only available in vector. Commented Oct 13, 2014 at 18:44

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

1 Comment

For me this swaps the first and last elements instead of just moving the first item to the back.
3

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

std::rotate( v.begin(), v.begin() + 1, v.end() );

3 Comments

std::vector doesn't have a pop_front(), for a good reason. It would be quite inefficient.
Your new version would "work", but is unnecessarily inefficient.
@juanchopanza Why, is it O(N)?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.