/*
Removes an element from an unordered vector, i.e. the
ordering of the elements in the vector isn't important.
v = a vector
pos = the position of the element to be erased
its value comes from keyboard user input
Algorithm:
Last element of vector is 1st copied to position pos.
Last element is then eliminated & the size of
the vector is decreased by one using pop_back.
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void erase(vector<string>& v, int pos);
// Precond: vector must have at least 1 value
// pos must be a non-negative int
// postcond: element at position pos is erased from the vector by
// replacing it with the last element of the vector
// and the size of the vector is then reduced by 1
void print(const vector<string>& v);
// Precond: vector must have at least 1 value
// Postcond: content of vector printed to screen
// Purpose:
// Prints all elements in a vector.
// v = the vector to be printed
int main( )
{
vector<string> staff(5);
staff[0] = "Hacker, Harry";
staff[1] = "Reindeer, Rudolf";
staff[2] = "Cracker, Carl";
staff[3] = "Lam, Larry";
staff[4] = "Sandman, Susan";
print(staff);
int pos;
cout << "Remove which element? ";
cin >> pos;
erase(staff, pos);
print(staff);
return 0;
}
void print(const vector<string>& v)
{
// Precond: vector must have at least 1 value
// Postcond: content of vector printed to screen
for (unsigned i = 0; i < v.size( ); i++)
cout << "[" << i << "] " << v[i] << "\n";
}
void erase(vector<string>& v, int pos)
{
// Precond: vector must have at least 1 value
// pos must be a non-negative int
// postcond: element at position pos is erased from vector
// replaced by the last element of vector and the
// the size of the vector is reduced by 1
// copy last element to position pos
v[pos] = v[v.size( ) - 1];
// reduce size of the vector by 1
v.pop_back( );
}