如何更改C ++ STL向量的特定元素(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);
}
现在,例如, 如何将矢量的5th element更改为-1 ?
我试过l.assign(4, -1); 它不像预期的那样行事。 其他矢量方法似乎都不适合。
我已经使用了矢量,因为我需要在我的代码中使用随机访问功能(使用l.at(i) )。
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)).
最满意答案
at和operator[]都返回索引元素的引用,所以你可以简单地使用:
l.at(4) = -1;要么
l[4] = -1;at and operator[] both return a reference to the indexed element, so you can simply use:
l.at(4) = -1;or
l[4] = -1;更多推荐
发布评论