I’m having trouble with using vectors, iterators and then using const.
For a bit of context I’m trying to create a write method for a vector<string> so I can easily print out all the strings within the vector.
Here’s the bit of code:
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;
}
When I try this I end up getting an error on line 2:
cannot convert from ‘
std::_Vector_const_iterator<_Myvec>‘ to ‘std::_Vector_iterator<_Myvec>‘.
So I have to remove the const from the end of the write method, and then for the operator<< to work I have to remove the const from the rhs parameter.
Why is this? I am not trying to change any class members, so I don’t understand what’s going on… What is it I am missing?
It’s like the compiler is telling you. Use
instead of
so
would work. Make sure to use != instead of < when comparing to end().