Thread: removing elements from a vector

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    222

    removing elements from a vector

    Hi,

    What I'm trying to do is to remove elements from my vector. Generally the idea is to do something like this:

    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    
    int main (){
    
      vector<string> vec;
    
      for (int i =0; i< 10; i++)
        vec.push_back("abcdefghijk"+to_string((long long)i));
    
      for(int k = 0 ; k< vec.size();k++){ //bla bla bla
        if(k==5 || k==7)
            vec.erase(vec.begin()+k);
    
      }
      for (int i =0; i< vec.size(); i++)
        cout << vec[i] << endl;
    
    return 0;
    
    }
    but in this case each time i remove an elament i need to recompute the index of the next element. So let say I want to remove the 5th and 7th element. the above algorithm will remove 5th with no problem but the 7th is not 7th any more but 6th. is there a clean way to do this without me explicitly recomputing the index position in each cycle. also is there a faster way to do this ?

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. removing duplicate elements from an array
    By Pulock2009 in forum C Programming
    Replies: 3
    Last Post: 11-06-2013, 01:25 PM
  2. Removing elements from an array of linked list
    By koplersky in forum C Programming
    Replies: 13
    Last Post: 10-08-2012, 02:04 PM
  3. Removing elements from an array
    By monki000 in forum C++ Programming
    Replies: 3
    Last Post: 03-30-2010, 12:23 PM
  4. Replies: 14
    Last Post: 12-02-2007, 03:32 AM
  5. Newbie needs help removing elements from an array
    By daki76 in forum C++ Programming
    Replies: 10
    Last Post: 06-20-2006, 09:42 AM