Using the vector<type>::iterator With const
Posted: Sun May 17, 2009 7:42 pm
So after Marauder gave me some sound advice, I've been trying to implement the use of iterators into my for loops. However, being the diligent little code monkey I am, I've been trying to use the const keyword wherever I can, and the two concepts are not playing nicely 
So when I pass a vector to a display function, I use the format:
void display( const vector<type>& data )
which, obviously, allows me to pass by reference and still protect the data in my vector (since a display function should not be allowed to manipulate my data, right)
So anyway, if I try to use the iterator for looping through my vector (which is a const reference), I get an error. I made a simple program to illustrate the error:
So as you can see, we get a type mismatch. I suppose I could remedy this by making a copy of my vector and looping through the copy, but that would take time. My question is: What are the possible solutions for this? Which would tax the system the least or take the least time?

So when I pass a vector to a display function, I use the format:
void display( const vector<type>& data )
which, obviously, allows me to pass by reference and still protect the data in my vector (since a display function should not be allowed to manipulate my data, right)
So anyway, if I try to use the iterator for looping through my vector (which is a const reference), I get an error. I made a simple program to illustrate the error:
Code: Select all
#include <iostream>
#include <vector>
using namespace std;
void display( const vector<int>& data );
int main()
{
vector<int> nums;
display( nums );
}
void display( const vector<int>& data )
{
for( vector<int>::iterator i = data.begin() ; i != data.end() ; ++i )
{
cout << *i << endl;
}
}
Code: Select all
Error 1 error C2440: 'initializing' : cannot convert from 'std::_Vector_const_iterator<_Ty,_Alloc>' to 'std::_Vector_iterator<_Ty,_Alloc>'