简体   繁体   English

C ++ std :: vector-如何修改由迭代器指定的元素?

[英]C++ std::vector - How to modify an element specified by an iterator?

I am trying to change each element of a vector, but my code doesn't compile, because of some confusion over const s. 我正在尝试更改向量的每个元素,但是由于对const的混淆,我的代码无法编译。 Here is a greatly simplified example (I have omitted the initialization of the vector): 这是一个大大简化的示例(我省略了向量的初始化):

std::vector<int> test;
for (auto iter = test.cbegin(); iter != test.cend(); ++iter)
{
    int v = *iter; // gets the correct element
    *iter = v * 2; // compile error
}

The compiler error is "'iter': you cannot assign to a variable that is const". 编译器错误为“'iter':您无法分配给const变量”。 What is the correct way to modify a single element, using iterators as shown? 如图所示,使用迭代器修改单个元素的正确方法是什么?

You specifically asked compiler to make sure you will not modify the content of the vector by using cbegin() . 您专门要求编译器确保使用cbegin()修改矢量的内容。

If you want to modify it, use non-const functions: 如果要修改它,请使用非const函数:

for(auto iter = test.begin(); iter != test.end(); ++iter)
{
    int v = *iter; // gets the correct element
    *iter = v * 2; // works
}

Or shorter version of the above loop using range-based loop: 或者使用基于范围的循环,上述循环的较短版本:

for(auto& v : test)
{
    v *= 2;
}

There is a difference between types of iterators: 迭代器的类型有所不同:

std::vector<int>::const_iterator a // not allowed to modify the content, to which iterator is pointing
*a = 5; //not allowed
a++; //allowed

const std::vector<int>::iterator b //not allowed to modify the iterator itself (e.g. increment it), but allowed to modify the content it's pointing to
*b = 5; //allowed
b++; //not allowed

std::vector<int>::iterator c //allowed to both modify the iterator and the content it's pointing to
*c = 5; //allowed
c++; //allowed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM