I have the following method:
void* vpArr_t::operator[](int i) const
{
if (!isEmpty() && i >= 0 && i < nOfItems)
{
list<void*>::iterator it;
int idx;
for(it = array.begin(), idx = 0; idx < i; ++it, ++idx); // go to the i'th element
return *it;
}
else
{
return NULL;
}
}
Where:
array
is a list type.
I'm getting a red underline (compilation error) in the following line:
for(it = array.begin(), idx = 0; idx < i; ++it, ++idx);
at:
it = array.begin()
it says that I'm tring to set a list<void*>::const_iterator
into a list<void*>::iterator
type.
But I noticed that there's a iterator
overloading for the begin()
method. how to solve this error? I'm using Visual C++ 2012.
Presumably
array
is a data member, and you are in aconst
member function, so you cannot call non-const methods on data members. So you need aconst_iterator
:Try
list<void*>::const_iterator it
instead:array
is probably a const reference or a member variable in the class not marked asmutable
. Your function is marked as const so member data cannot be modified within it.Presumably,
array
is a member ofvpArr_t
. Since thisvpArr_t::operator[]
overload is declaredconst
, the members ofvpArr_t
are effectively alsoconst
. This ensures that you do not modify thevpArr_t
object's state. Sincearray
is effectivelyconst
, when you callbegin
on it, you get aconst_iterator
.Since you aren't actually modifying the contents of
array
, you should change your iterator type toconst_iterator
:If you do actually want to use a non-
const
iterator because you want to modify the contents ofarray
, you'll need to makeoperator[]
a non-const
function.Apart from the fact that you can't use
iterator
but have to useconst_iterator
, there is a function that can help you:That said, calling a doubly-linked list an array is questionable. Also, this isn't really efficient, using a
vector<>
ordeque<>
would give you constant-time access to the i-th element. Also, I would usesize_t
for the index, which is more consistent with the rest of the C++ standardlibrary.