Inserts an element into a vector at given position
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void insert(vector<string>& v, int pos, string s)
{
int last = v.size() - 1;
v.push_back(v[last]);
for (int i = last; i > pos; i--)
v[i] = v[i - 1];
v[pos] = s;
}
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 << "Insert before which element? ";
cin >> pos;
insert(staff, pos, "New, Nina");
print(staff);
return 0;
}
Related examples in the same category