stan
stan

Reputation: 4995

c++ iterator confusion

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.

Upvotes: 2

Views: 772

Answers (6)

Phillip Ngan
Phillip Ngan

Reputation: 16126

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 []
}

Upvotes: 4

csj
csj

Reputation: 22426

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();

Upvotes: 4

sap
sap

Reputation: 1228

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.

Upvotes: 0

John Weldon
John Weldon

Reputation: 40799

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()

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308530

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.

Upvotes: 2

Naveen
Naveen

Reputation: 73503

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

Upvotes: 2

Related Questions