我在使用 vector 、迭代器然后使用 const
时遇到问题.
对于一些上下文,我正在尝试为 vector<string>
创建一个写入方法这样我就可以轻松地打印出 vector 中的所有字符串。
代码如下:
void ArrayStorage::write(ostream &sout) const{
for (vector<string>::iterator stringIt = _dataVector.begin();
stringIt < _dataVector.end();
stringIt++){
sout << *stringIt;
}
}
ostream& operator<<(ostream &sout, const ArrayStorage &rhs){
rhs.write(sout);
return sout;
}
当我尝试这样做时,我最终在第 2 行收到错误:
cannot convert from '
std::_Vector_const_iterator<_Myvec>
' to 'std::_Vector_iterator<_Myvec>
'.
所以我必须删除 const
从 write 方法的末尾开始,然后为 operator<<
工作我必须删除 const
来自 rhs 参数。
这是为什么?我不想改变任何类(class)成员,所以我不明白发生了什么......我错过了什么?
最佳答案
这就像编译器告诉你的一样。使用
::const_iterator
代替
::iterator
所以
for (vector<string>::const_iterator stringIt = _dataVector.begin();
stringIt != _dataVector.end();
++stringIt){
sout << *stringIt;
}
会起作用。与 end() 比较时,请务必使用 != 而不是 <。
关于c++ - 在使用 vector 和迭代器时与 const 行为作斗争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9453664/