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

时间:2012-02-26 13:57:00

标签: c++ vector iterator const

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

对于一些上下文,我正在尝试为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;
}

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

  

无法从“std::_Vector_const_iterator<_Myvec>”转换为“std::_Vector_iterator<_Myvec>”。

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

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

1 个答案:

答案 0 :(得分:6)

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

::const_iterator

而不是

::iterator

所以

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

会奏效。一定要使用!=而不是&lt;与end()比较时。