Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ iterator confusion

Tags:

c++

iterator

stl

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.

like image 328
stan Avatar asked Nov 18 '25 20:11

stan


1 Answers

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 []
}
like image 142
Phillip Ngan Avatar answered Nov 20 '25 12:11

Phillip Ngan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!