Moeb Moeb - 1 month ago 5
C++ Question

How to change a particular element of a C++ STL vector

vector<int> l;
for(int i=1;i<=10;i++){
l.push_back(i);
}


Now, for example, how do I change the
5th element
of the vector to
-1
?


I tried
l.assign(4, -1);

It is not behaving as expected. None of the other vector methods seem to fit.

I have used vector as I need random access functionality in my code (using
l.at(i)
).

Answer

at and operator[] both return a reference to the indexed element, so you can simply use:

l.at(4) = -1;

or

l[4] = -1;
Comments