c++ iterator vector struct

21,417

You have to dereference the iterator and use it like

(*it).min

or

(*it).max

or, without de-referencing,

it->min

The type of the dereferenced iterator (*it) SHOULD be C_Cell, as that's how iterators work, their operator* returns a reference to an object of the underlying type of the container. Iterators behave very much like regular pointers (although they are not regular pointers, but proxy classes), you can increment/dereference etc.

Share:
21,417
Mau
Author by

Mau

Updated on November 24, 2020

Comments

  • Mau
    Mau over 3 years

    I created a struct with two fields of type Point3f (which is inherited from another header).

    struct C_Cell {
    
      Point3f min, max;
    
    };
    

    then I created a vector of C_Cell

    std::vector< C_Cell> grid;

    and I have filled through grid.push_back(c) where c is a C_Cell.

    Now, when I try to iterate the vector, through

    for (std::vector<C_Cell>::iterator it = grid.begin() ; it != grid.end(); ++it)

    during debugging, the type of it isn't C_Cell but Point3f, which is the type of the field, moreover empty.

    How can I iterate correctly, in such a way to obtain a single element of type C_Cell?

    Thanks ( and sorry for my english! :) )

    • jww
      jww over 9 years
      Your title is a collection of tags. Its pretty much worthless, and few people will bother with it since you did not take the time with your question. You should use the title to summarize your question or problem.
    • Mau
      Mau over 9 years
      right... you have reason. sorry and thanks
    • WillC
      WillC over 7 years
      First result in Google for my search "cpp vector iterator struct" though.
  • Mau
    Mau over 9 years
    yes, of course, but in debugging it->min result of type point3d. in fact the object is empty.
  • vsoftco
    vsoftco over 9 years
    @user3641602 it->min has the type Point3f, as you point inside the structure. My guess is that you don't initialize the structure before pushing it back into the vector. Make sure that before push_back(c), c is an initialized structure.
  • vsoftco
    vsoftco over 9 years
    @user3641602 then just try to post a minimal compilable example, from your code there is no way of saying what else could go wrong. Can you at least e.g. cout << (it->min).member lines inside the for and see what is being printed at runtime?