Thread: move element in a vector

  1. #1
    Registered User
    Join Date
    May 2006

    move element in a vector


    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
    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
    I think you can use rotate() from <algorithm>.

  4. #4
    The larch
    Join Date
    May 2006
    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, 11:30 PM
  2. Replies: 2
    Last Post: 03-24-2006, 08:36 PM
  3. The proper way to erase a vector element
    By misplaced in forum C++ Programming
    Replies: 10
    Last Post: 03-27-2005, 11: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, 07:33 PM