Replacing value in Vector

Jan 19, 2009 at 6:42am
Given a vector myvec, which contain [0,0,0,0].
and variables: int pos = 3; int nval =4;.

I rant to replace the pos-th entry of myvec with nval,
yielding [0,0,0,4].

How can I achieve that? I'm stuck with the following
function


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vector <int> neighbors(vector<int>& arg, int posNo, int baseNo) {
    // pass base position and return neighbors
                         
    vector <int> transfVec;   
    vector <int> temp;   

    temp = arg[posNo];
    //temp = ??
    

    transfVec = temp;    

    return transfVec;    

}



Last edited on Jan 19, 2009 at 6:42am
Jan 19, 2009 at 6:53am
I think you can use the [] operator on a vector to access any location freely. However, since this ignores the bounds of memory the vector has reserved, you will likely need to manually resize the vector unless you know for certain that the location you are editing is valid memory.
Jan 19, 2009 at 10:38pm
It should be a 2-line function. No need to return a value if the vector<> is taken by non-const reference; just change it in place.
Topic archived. No new replies allowed.