Inserts an element into a vector at given position : vector insert « Vector « C++






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

1.Insert element by index
2.Insert element at specific position
3.Insert 10 duplicate value to vector
4.Insert one vector to another vector
5.Insert elements from array
6.Combine insert and end to add elements to the end of vector
7.Insert characters into vector. An iterator to the inserted object is returned
8.Create and initialize vector with float number array
9.Appending values to Vector Containers after sorting