move element in a vector

This is a discussion on move element in a vector within the C++ Programming forums, part of the General Programming Boards category; Hello I have an easy question. How can I move element in a vector so that it will be first ...

  1. #1
    l2u
    l2u is offline
    Registered User
    Join Date
    May 2006
    Posts
    630

    move element in a vector

    Hello

    I have an easy question.
    How can I move element in a vector so that it will be first in the list and other elements will move one place forward?
    What is the easiest way? Should I better go for another container for this kind of purpose?

    Thanks for help

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    If you're doing this a lot it may be expensive with a vector, but other containers have other disadvantages so it depends on the rest of the circumstances.

    As far as how you do it, you would probably have to erase the element from the vector and then insert it at position 0.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    I think you can use rotate() from <algorithm>.

    http://www.cplusplus.com/reference/a...hm/rotate.html

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    A deque might be more happy about insertions in the beginning.

    But it seems that you also want to take the element out of the container first (not necessarily from the end?) which might be something a list is better at.

    The choice of container might depend on questions such as do you have a lot of data and are you planning to do this operation often, and what else do are you going to do with it.

    If a vector is good, I guess using rotate on the range from begin to the element you want to get to the front sounds OK.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 01-05-2008, 10:30 PM
  2. Replies: 2
    Last Post: 03-24-2006, 07:36 PM
  3. The proper way to erase a vector element
    By misplaced in forum C++ Programming
    Replies: 10
    Last Post: 03-27-2005, 10:00 AM
  4. Vector Element spontaneously changing?!
    By homgran in forum C Programming
    Replies: 6
    Last Post: 05-28-2004, 09:34 PM
  5. Operators for 3D Vector Mathematics
    By Anarchist in forum C++ Programming
    Replies: 10
    Last Post: 01-31-2003, 06:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21