Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator for vector of pointers not dereferencing correctly

Here is my issue:

I have a std::vector<AguiWidgetBase*> which is used to keep track of child controls.

I have these two functions to return iterators:

std::vector<AguiWidgetBase*>::const_iterator AguiWidgetBase::getChildBeginIterator() const
{
    return children.begin();
}

std::vector<AguiWidgetBase*>::const_iterator AguiWidgetBase::getChildEndIterator() const
{
    return children.end();
}

I then use it like this:

for(std::vector<AguiWidgetBase*>::const_iterator it = box->getChildBeginIterator(); 
    it != box->getChildEndIterator(); ++it)
{
    it->setText("Hello World");
}

and I get these errors:

Error   3   error C2039: 'setText' : is not a member of 'std::_Vector_const_iterator<_Ty,_Alloc>'   c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\main.cpp   112
Error   2   error C2839: invalid return type 'AguiWidgetBase *const *' for overloaded 'operator ->' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\main.cpp   112

Why is it giving me these errors?

Thanks

like image 565
jmasterx Avatar asked Oct 13 '10 02:10

jmasterx


People also ask

How do you dereference an iterator?

3. Dereferencing: An input iterator can be dereferenced, using the operator * and -> as an rvalue to obtain the value stored at the position being pointed to by the iterator. 4. Incrementable: An input iterator can be incremented, so that it refers to the next element in the sequence, using operator ++().

Is iterator a pointer in vector?

An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container.

Can you dereference end iterator?

In this code fragment the user's inten- tion is clear: transmogrify each of the elements in values and insert them at the end of results. Since it is illegal, however, to dereference or increment the end iterator of a container and therefore illegal to write using it, such code is always semantically incorrect.

Can you dereference twice?

You dereference it once you get the pointer it was pointing to, dereference it twice you get the object pointed to by the pointer ptr_ptr is pointing to.


2 Answers

Because an iterator acts like a pointer, and in this case a pointer to a pointer.

You'd need:

(*it)->setText("Hello World"); // dereference iterator, dereference pointer
like image 195
GManNickG Avatar answered Sep 21 '22 10:09

GManNickG


Is there a way I can change my iterators so that it-> works?

Not directly, but you could do something like:

for(std::vector<AguiWidgetBase*>::const_iterator it = box->getChildBeginIterator(); 
    it != box->getChildEndIterator(); ++it)
{
    AguiWidgetBase* p = *it;

    p->setText("Hello World");
}
like image 32
TheUndeadFish Avatar answered Sep 22 '22 10:09

TheUndeadFish