如何更改 C++ STL 向量的特定元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2624232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change a particular element of a C++ STL vector
提问by Moeb
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
?
现在,例如,如何5th element
将向量的更改为-1
?
I tried l.assign(4, -1);
It is not behaving as expected. None of the other vector methods seem to fit.
我试过l.assign(4, -1);
它没有按预期运行。其他向量方法似乎都不适合。
I have used vector as I need random access functionality in my code (using l.at(i)
).
我使用了 vector,因为我需要在我的代码中使用随机访问功能(使用l.at(i)
)。
回答by James McNellis
at
and operator[]
both return a reference to the indexed element, so you can simply use:
at
并且operator[]
都返回对索引元素的引用,因此您可以简单地使用:
l.at(4) = -1;
or
或者
l[4] = -1;
回答by rbaleksandar
Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.
尽管@JamesMcNellis 的答案是有效的,但我想解释一些有关错误处理的内容,以及还有另一种方法可以做您想做的事情。
You have four ways of accessing a specific item in a vector:
您有四种访问向量中特定项目的方法:
- Using the
[]
operator - Using the member function
at(...)
- Using an iterator in combination with a given offset
- Using
std::for_each
from thealgorithm
header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.
- 使用
[]
运算符 - 使用成员函数
at(...)
- 将迭代器与给定的偏移量结合使用
std::for_each
从algorithm
标准 C++ 库的头文件中使用。这是我可以推荐的另一种方式(它在内部使用迭代器)。例如,您可以在此处阅读有关它的更多信息。
In the following examples I will be using the following vector as a lab rat and explaining the first three methods:
在以下示例中,我将使用以下向量作为实验鼠并解释前三种方法:
static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));
This creates a vector as seen below:
这将创建一个向量,如下所示:
1 2 3 4
First let's look at the []
way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possiblyyou access the item you want. I say possiblybecause the []
operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:
首先让我们看看[]
做事的方式。它的工作方式与您在使用普通数组时所期望的方式几乎相同。您提供一个索引,并可能访问您想要的项目。我说可能是因为[]
操作员没有检查向量是否真的有那么多项目。这会导致无提示的无效内存访问。例子:
v[10] = 9;
This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100
instead of 234
, which is somewhat connected to that very location where you retrieve an item from you vector.
这可能会也可能不会导致即时崩溃。最坏的情况当然是如果它没有并且您实际上得到了似乎是有效值。与数组类似,这可能会导致浪费时间试图找出原因,例如,在 1000 行代码之后,您会得到一个值100
而不是234
,这在某种程度上与您从向量中检索项目的位置有关。
A much better way is to use at(...)
. This will automatically check for out of bounds
behaviour and break throwing an std::out_of_range
. So in the case when we have
更好的方法是使用at(...)
. 这将自动检查out of bounds
行为并中断抛出std::out_of_range
. 所以当我们有
v.at(10) = 9;
We will get:
我们将获得:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)
在抛出 'std::out_of_range'
what()的实例后调用终止:vector::_M_range_check: __n(即 10)>= this->size()(即 4)
The third way is similar to the []
operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:
第三种方式类似于[]
操作符,你可以把事情搞砸。与数组一样的向量是包含相同类型数据的连续内存块序列。这意味着您可以通过将起始地址分配给迭代器来使用起始地址,然后只需向该迭代器添加偏移量即可。偏移量仅代表您要遍历的第一项之后的项数:
std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9; // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...
As you can see we can also do
正如你所看到的,我们也可以做到
*(it+10) = 9;
which is again an invalid memory access. This is basically the same as using at(0 + offset)
but without the out of bounds error checking.
这又是无效的内存访问。这与 using 基本相同,at(0 + offset)
但没有越界错误检查。
I would advice using at(...)
whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the []
operator.
我建议at(...)
尽可能使用,不仅因为它比迭代器访问更具可读性,而且因为我在上面提到的带有偏移组合的迭代器和[]
运算符的无效索引的错误检查。
回答by Fred Larson
This should do it:
这应该这样做:
l[4] = -1
回答by Tom
回答by codexaxor
I prefer
我更喜欢
l.at(4)= -1;
while [4] is your index
而 [4] 是您的索引