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

系统教程 行业动态 更新时间:2024-06-14 17:04:03
如何更改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;

更多推荐

本文发布于:2023-04-24 21:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/78cd9a1268460f29fe662addd595a3f2.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   如何更改   元素   STL   vector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!