使用向量和迭代器时遇到const行为

Idi*_*die 1 c++ iterator const vector

我在使用向量,迭代器然后使用时遇到了麻烦const.

对于一些上下文,我正在尝试为a创建一个write方法,vector<string>因此我可以轻松地打印出向量中的所有字符串.

这是一些代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试这个时,我最终得到第2行的错误:

无法从' std::_Vector_const_iterator<_Myvec>' 转换为' std::_Vector_iterator<_Myvec>'.

所以我必须const从write方法的末尾删除,然后为了operator<<工作我必须const从rhs参数中删除.

为什么是这样?我不是要改变任何班级成员,所以我不明白发生了什么......我错过了什么?

Tot*_*nga 6

这就像编译器告诉你的那样.使用

::const_iterator
Run Code Online (Sandbox Code Playgroud)

代替

::iterator
Run Code Online (Sandbox Code Playgroud)

所以

for (vector<string>::const_iterator stringIt = _dataVector.begin();
                stringIt != _dataVector.end();
                ++stringIt){
    sout << *stringIt;
}
Run Code Online (Sandbox Code Playgroud)

会工作.确保在与end()比较时使用!=而不是<.