tags:

views:

143

answers:

6

I have a vector<list<customClass> >

I have an iterator vector<list<customClass> >::const_iterator x

When I try to access an member of customClass like so:

x[0]->somefunc(), I get errors of a non-pointer type/not found.

+2  A: 

iterator class does not provide operator[] hence you can not use it like that . You should use it as x->somefunc()

Naveen
But that won't point to the actual class. Is there someway to not point to the list but to the class
Stanislav Palatnik
For that you have to use two levels of indirection. Get the list object from the first iterator . Then get the iterator in to the list object , dereference this iterator to get someclass object
Naveen
since x is an iterator for a vector, it is a random access iterator. as such, it provides operator[]. The result, however, is a const lvalue of a std::list that doesn't provide "->".
sellibitze
+2  A: 

x is an iterator, which acts like a pointer - it points to a list. So you can only use functions which are members of std::list.

Mark Ransom
+2  A: 

The const iterator will dereference to a list<customClass> object not a pointer to that list. You'd have to access the index in that list for the class...

Ignoring error checking:

(*x)[0].somefunc()
John Weldon
stl lists don't overload the index operator
csj
Ah, thanks for the correction.
John Weldon
A: 

if you want direct access the list and vector class already implement the [] operator, so just access it directly: vectorObj[x].someFunc();

iterator are for going through the list (to iterate it like the name suggests), use it for that.

sap
+4  A: 

The iterator dereferences to a list. If you want to access an object in that list, then you will have to use the list methods to do so. However, since stl lists don't overload the index operator, that won't be a valid option.

This will let you call somefunc on the first element in the list:

(*x).front().somefunc();

On the other hand, if you want an iterator for your list, you can do something like this:

list<customClass>::const_iterator listIterator = (*x).begin();
listIterator->somefunc();
csj
+3  A: 

Here's a complete working snippet. To answer your question, the line with the comment [1] shows how to dereference the const_iterator, while comment [2] shows how to dereference using the operator [].

#include <vector>
#include <list>
#include <iostream>
class Foo
{
public:
    void hello() const
    {
        std::cout << "hello - type any key to continue\n";
        getchar();
    }

    void func( std::vector<std::list<Foo> > const& vec )
    {
        std::vector<std::list<Foo> >::const_iterator qVec = vec.begin();
        qVec->front().hello(); // [1] dereference const_iterator
    }
};
int main(int argc, char* argv[])
{
    std::list<Foo>  list;
    Foo foo;
    list.push_front(foo);
    std::vector<std::list<Foo> > vec;
    vec.push_back(list);

    foo.func( vec );
    vec[0].front().hello(); // [2] dereference vector using []
}
Phillip Ngan