[英]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.