繁体   English   中英

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

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

我正在尝试更改向量的每个元素,但是由于对const的混淆,我的代码无法编译。 这是一个大大简化的示例(我省略了向量的初始化):

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
}

编译器错误为“'iter':您无法分配给const变量”。 如图所示,使用迭代器修改单个元素的正确方法是什么?

您专门要求编译器确保使用cbegin()修改矢量的内容。

如果要修改它,请使用非const函数:

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

或者使用基于范围的循环,上述循环的较短版本:

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

迭代器的类型有所不同:

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