Can't assign List Iterator [C++]

2020-05-09 18:04发布

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.

4条回答
够拽才男人
2楼-- · 2020-05-09 18:36

Presumably array is a data member, and you are in a const member function, so you cannot call non-const methods on data members. So you need a const_iterator:

list<void*>::const_iterator it,
查看更多
闹够了就滚
3楼-- · 2020-05-09 18:45

Try list<void*>::const_iterator it instead: array is probably a const reference or a member variable in the class not marked as mutable. Your function is marked as const so member data cannot be modified within it.

查看更多
Summer. ? 凉城
4楼-- · 2020-05-09 18:48

Presumably, array is a member of vpArr_t. Since this vpArr_t::operator[] overload is declared const, the members of vpArr_t are effectively also const. This ensures that you do not modify the vpArr_t object's state. Since array is effectively const, when you call begin on it, you get a const_iterator.

Since you aren't actually modifying the contents of array, you should change your iterator type to const_iterator:

list<void*>::const_iterator it;

If you do actually want to use a non-const iterator because you want to modify the contents of array, you'll need to make operator[] a non-const function.

查看更多
\"骚年 ilove
5楼-- · 2020-05-09 18:54

Apart from the fact that you can't use iterator but have to use const_iterator, there is a function that can help you:

list<void*>::const_iterator it = arary.begin();
std::advance(it, i);

That said, calling a doubly-linked list an array is questionable. Also, this isn't really efficient, using a vector<> or deque<> would give you constant-time access to the i-th element. Also, I would use size_t for the index, which is more consistent with the rest of the C++ standardlibrary.

查看更多
登录 后发表回答