Mega Code Archive

 
Categories / C++ / Vector
 

Removes an element from an unordered vector

#include <iostream> #include <string> #include <vector> using namespace std; void erase(vector<string>& v, int pos) {      int last_pos = v.size() - 1;    v[pos] = v[last_pos];    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; }