tags:

views:

105

answers:

3
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)).

+10  A: 

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

l.at(4) = -1;

or

l[4] = -1;
James McNellis
And you'd better take the habit to use `at`, less idiomatic, but bound-checking is priceless.
Matthieu M.
@Matt: Though out of bounds errors tend to be a programmer fault, while `at` throws an exception. That is to say, an `assert` would be better, and I think both MSVC and gcc have checked iterators.
GMan
@GMan Personally, I've more or less stopped using asserts. I tend to use at() in situations where I might make a coding mistake (I wouldn't use one in a for-loop, for example) - something I'm just as likely to do when writing an assert.
anon
We don't use `assert` where I work. We have a test environment that is supposed to be stable, so that clients can test on it without being interrupted too often, and therefore we have a simili assert which throws instead of aborting the program... therefore `at` and `ASSERT` have the very same effect for me :)
Matthieu M.
+4  A: 

This should do it:

l[4] = -1
Fred Larson
+3  A: 

You can use the subscript operator

l[4] = -1
Tom