I decided to learn C++ STL and I was exprimenting with STL containers.
I saw this example here:

// inserting into a vector
#include <iostream>
#include <vector>
using namespace std;

int main ()    {
  vector<int> myvector (3,100);
  vector<int>::iterator it;

  it = myvector.begin();
  it = myvector.insert ( it , 200 );

  myvector.insert (it,2,300);

  // "it" no longer valid, get a new one:
  it = myvector.begin();

  vector<int> anothervector (2,400);
  myvector.insert (it+2,anothervector.begin(),anothervector.end());

  int myarray [] = { 501,502,503 };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    cout << " " << *it;
  cout << endl;

  return 0;

My question is why did they add 2 to it in the line myvector.insert (it+2,anothervector.begin(),anothervector.end());?. At first I thought it was because they inserted 2 items myvector.insert (it,2,300); but they later update it again it = myvector.begin(); so it is not because of that.

The constructor for the function is
void insert ( iterator position, InputIterator first, InputIterator last );
Is the position supposed to be location of the vector in which something is being inserted or something else?

use a pencil and paper to write out the values in the vector after each insertion into the original vector in the example you've posted.

Remember it is myvector.begin() and not another vector.begin(). it + 2 means start two positions beyond myvector.begin(), which would be position 3 of myvector. don't change it (myvector.begin).

Thanks. For some reason I was reading the output in the wrong order... don't ask :)

This question has already been answered. Start a new discussion instead.