Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2004
    Posts
    262

    Iterator dereference through another iterator.

    Hello all!

    Say I have a class with a vector and iterator in it.

    Code:
    class X
    {
       ...
        public:
           vector<double> x_vec;
           vector<double>::iterator x_vec_it;
       ...
    }
    The constructor sets up some values in the vector and sets the iterator to point at the beginning of the vector.

    Later I want to do this

    Code:
    ... somewhere else
    
    vector< X > AllXes;
    
    ...inserts some new objects into vector AllXes
    
    for(vector< X >::iterator AllXesIt = AllXes.begin(); AllXes )
    {
        //cout << ... the value that the iterator in the object that AllXesIt would be pointing to
       cout << AllXesIt->x_vec_it; //This is obviously not correct. I want to dereference x_vec_it
    }
    Dereferencing the first iterator, I can go

    Code:
        (*AllXesIt).SomeMemberFunction();
    But not

    Code:
       (*(*AllXesIt).x_vec_it); // or similar
    What is the syntax for doing this? I want to dereference the iterator that is a member of the class through an iterator to an object instance.

  2. #2
    Join Date
    Mar 2004
    Posts
    262
    Of course I am having a brain melt-down! The obvious solution is make a member function which returns the value in question... But still on a technical side is that kind of dereferencing possible?

  3. #3
    Join Date
    Oct 2006
    Posts
    1,548
    You really dont want to be storing iterators like that. Unless you know for sure that Vector isnt going to change its state.

    Either way, just do the "right" thing and dont store iterators like that
    Last edited by wforl; 12-08-2010 at 05:53 AM.
    [quote][\quote]

  4. #4
    Join Date
    Mar 2004
    Posts
    262
    Yeah, I guess I know but I was a bit stressed and wanted to have an iterator for each vector auto-made for me. Its for a really special case... it also involves recursions..
    Anyway, I found out the root cause of my problem. I pointed the iterator to the beginning of the vector inside the constructor. As the object doesn't really exist until after the constructor finishes (I assume...) it can't really know where the vector is going to end up so I just got garbled results when I dereferenced it. Thus, I did manage to do what I tried to do, it just wasn't what I wanted. After setting the iterator to the start of the vector from a another function call after the object was instantiated, everything worked as I expected. Live and learn...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •