Basic insertion in vector: why this insertion doesn't work?

Mar 12, 2020 at 10:53pm
hello, If I want to insert a value given a certain index, sorry can you tell me what I am missing here. Reading the documentation I was under the impression that this should work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>

using namespace std;

int main() 
{
    vector<int> v {1,2,3,5};

    int index = 0;
    int value = 9;
    //I would expect index 0 to contain value=9
    v.insert(v.begin(), index, value);
    cout << v.at(0); // this returns 1 still. Not 9.
    return 0;
}
Mar 12, 2020 at 11:06pm
Set 'index' to 1. Then rename it as
number_of_values_to_be_inserted.
Mar 12, 2020 at 11:20pm
I see the change now.
but what happens if I want to insert at position#3 for example?
is that why some examples are using iterators...
Mar 12, 2020 at 11:39pm
I will try to erase the existing value, then insert the new one.
Mar 13, 2020 at 12:22am
You're using the wrong proto. The one you use here is to insert multiples values, but what you want to do is v.insert(v.begin() + index, value);
Topic archived. No new replies allowed.