IdiotCoderCodie
IdiotCoderCodie

Reputation: 85

Struggling with const behaviour when using vectors and iterators

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?

Upvotes: 1

Views: 1277

Answers (1)

Totonga
Totonga

Reputation: 4366

It's like the compiler is telling you. Use

::const_iterator

instead of

::iterator

so

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

would work. Make sure to use != instead of < when comparing to end().

Upvotes: 6

Related Questions