Friday, April 8, 2011

Accessing vector elements inside another vector through an iterator?

std::vector< std::vector<coords> >::iterator iter;
for(iter = characters.begin(); iter != characters.end(); iter++) 
{
 std::vector<coords>* cha = iter; // doesn't work.
}

// does work.
std::vector<coords>* character = &characters.at(0);
coords* first = &character->at(0);

And I don't get why. Isn't iter supposed to be a pointer to an element of the type that it's container is supposed to 'contain'?

Anyone willing to shed light on this?

By doesn't work I mean:

error C2440: 'initializing' : cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' to 'std::vector<_Ty> *'

Which doesn't make a whole lot of sense to me.

From stackoverflow
  • An iterator is a type that can be dereferenced like a pointer, i.e., it has an explicit operator*() and operator->(). It doesn't have to be a pointer.

    So use &*iter if you want to get the address of the vector.

  • To clarify further on MSN's answer, you can think of the iterator as a wrapper to an individual item of the container, but it also has some smarts for incrementing (++iter), decrementing (++iter) etc. Remember, the underlying data structure may not be a contiguous block of memory depending on the container type / implementation. To access the actual value, you can

    1) derefence the iterator, eg

    Type t = *iter;

    2) treat the iterator as a pointer to the container type, eg

    iter->someFuncOnTheContainerType();

  • I know it's obvious now (in hindsight), but in your for loop you could also try:

    std::vector<coords> & cha = * iter;
    

    Also, not what you are asking for, and just FYI, but vectors support random access iterators. Meaning you could also write:

    for( size_t i=0; i<characters.size();  i ++ )
    

    And, if you needed to convert back to an iterator, you could use:

    characters.begin() + i
    

    It's not the C++ way of doing things, it breaks the generic iterator philosophy, but it has its uses.

0 comments:

Post a Comment