Inserting a value into a vector at a designated position

May 30, 2016 at 8:27pm
I have a vector (of ints); and I want to insert a new int at a specified position, n.

vector has an insert method, but requires an iterator to specify the position.

How can I obtain an iterator to the specified position without iterating from begin() for n places?

Thanks, Buk.
Last edited on May 30, 2016 at 8:46pm
May 30, 2016 at 8:42pm
vector.begin() + i gives an iterator positioned at index i of the vector.
May 30, 2016 at 8:43pm
Just add n to begin().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main ()
{
  vector<int> numbers = {1,2,3,4,5,6,7,8,9,10};
  cout << "Original vector : \n";
  copy (numbers.begin(), numbers.end(), ostream_iterator<int>(cout, " "));
  numbers.insert (numbers.begin () + 5, 99);
  cout << "\nAfter inserting 99 at position 5 : \n";
  copy (numbers.begin (), numbers.end (), ostream_iterator<int> (cout, " "));
  system ("pause");
  return 0;
}
May 30, 2016 at 9:02pm
Perfect. Thanks guys.

(Is there some way I might have derived information that from the docs http://www.cplusplus.com/reference/vector/vector/begin/ ?)
May 30, 2016 at 9:13pm
All random access iterators can be added with an integer to give another random access iterator into the same container.

http://www.cplusplus.com/reference/iterator/RandomAccessIterator/
May 30, 2016 at 9:30pm
Why did you look at the documentation for vector.begin() instead of vector.insert()? Your question did state that your question was about the vector.insert() function. The vector.insert() does show adding an int to begin().

http://www.cplusplus.com/reference/vector/vector/insert/

1
2
3
4
 it = myvector.begin();

  std::vector<int> anothervector (2,400);
  myvector.insert (it+2,anothervector.begin(),anothervector.end());
Topic archived. No new replies allowed.