我在使用向量,迭代器然后使用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>
”。
所以,我必须从写入方法的末尾删除const
,然后为operator<<
工作,我必须从RHS参数中删除const
。
这是为什么?我不想改变任何班级成员,所以我不明白发生了什么......我错过了什么?
Totonga的回答应该是正确的。此外,你的循环应该看起来像这样:for(vector :: iterator stringIt = _dataVector.begin(); stringIt **!= ** _dataVector.end(); stringIt ++){...}通常只有随机存取迭代器支持** <** or **> **。 –
alfa
2012-02-26 14:05:58
除了在帖子中黑入HTML,请点击组合窗格旁边的'?'按钮以了解如何格式化SO上的帖子。 – 2012-02-26 14:06:13