Removes an element from an ordered vector : vector erase « Vector « C++






Removes an element from an ordered vector

  
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void erase(vector<string>& v, int pos)
{ 
   for (int i = pos; i < v.size() - 1; i++)
      v[i] = v[i + 1];
   v.pop_back();
}

void print(vector<string> v){  
   for (int i = 0; i < v.size(); i++)
      cout << "[" << i << "] " << v[i] << "\n";
}

int main()
{  
   vector<string> staff(5);
   staff[0] = "A";
   staff[1] = "B";
   staff[2] = "C";
   staff[3] = "D";
   staff[4] = "E";
   print(staff);

   int pos;
   cout << "Remove which element? ";
   cin >> pos;

   erase(staff, pos);
   print(staff);
   return 0;
}
  
    
  








Related examples in the same category

1.Remove(delete) all elements in the vector
2.Erase first element
3.Use unique_copy to remove duplicate words
4.Removes an element from an unordered vector