Thread: Shifting back <vector> items...

  1. #1
    Registered User
    Join Date
    Jun 2002

    Angry Shifting back <vector> items...

    I have a vector filled with a structure. Now, I do
    pMyVec.erase (pMyVec.begin() + 2) for example.

    Now.. my question. Will pMyVec[2] still work for the next item? or do I have to shift back the items following the iterator I erased?
    Y3K Network
    Bringing the software of the future on the net.

  2. #2
    Registered User
    Join Date
    Jul 2003
    I think when you erase elements from vectors the elements after it are moved up.

  3. #3
    Registered User
    Join Date
    Jan 2003
    The index is still valid MyVec[2] is a copy of MyVec[3], MyVec[3] now contains MyVec[4] and so on. If you are going to be doing this a lot and you need to preserve order your best bet is with a list. If the order doesn't matter copy the last element to the element you want to delete and delete the last element.

    MyVec[2] = MyVec.back();
    Note that sometimes you get even better performance by swapping the element with the last element as often a swap can be implemented in terms of swapping pointers rather than a deep copy

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Welcome to and AI Horizon's Message Board
    By kermi3 in forum General AI Programming
    Replies: 9
    Last Post: 06-04-2009, 01:25 AM
  2. Retail Outlet Managment System - the 4th
    By Presidentofusa in forum C Programming
    Replies: 3
    Last Post: 11-10-2007, 10:44 PM
  3. Create new combo boxes based on items selected in preview combo box
    By RealityFusion in forum Windows Programming
    Replies: 2
    Last Post: 01-10-2007, 09:50 AM
  4. Back to programming?
    By Korwin in forum A Brief History of
    Replies: 1
    Last Post: 01-23-2002, 06:51 AM
  5. Its a shame for most ppl, but.... Ill be back....
    By Null Shinji in forum A Brief History of
    Replies: 0
    Last Post: 12-09-2001, 02:59 AM