如何更改C ++ STL向量的特定元素 [英] How to change a particular element of a C++ STL vector

查看:52
本文介绍了如何更改C ++ STL向量的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如,现在如何将向量的第5个元素更改为 -1 ?

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

我尝试了 l.assign(4,-1); 它的行为不符合预期.其他矢量方法似乎都不适合.

I tried l.assign(4, -1); It is not behaving as expected. None of the other vector methods seem to fit.

我使用了vector,因为我需要在代码中使用随机访问功能(使用 l.at(i)).

推荐答案

at operator [] 都返回对索引元素的引用,因此您可以简单地使用:

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

l.at(4) = -1;

l[4] = -1;

这篇关于如何更改C ++ STL向量的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆