Use Iterator to obtain vector index

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • randysimes
    New Member
    • Oct 2009
    • 54

    Use Iterator to obtain vector index

    I am creating a sorted vector using lower_bound. I set an Iterator to lower_bound to determine the place a 'val' needs to be. I then PushBack(val) to create the needed space for the item. I have tried several methods to then move the the 'val' from the back to it's lower_bound location, but either get a segfault or the items are not in "less than" order. I can easily do this using the 'index' of the items vs. trying to use Iterators. How can I calculate the index of the Iterator for lower_bound? Wait, now that I'm writing this, I have an idea. Can I start at Begin() and have a variable to 'count' up to the lower_bound?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Why don't you just use the member function vector<>::inser t?

    Your method is almost bound to fail at some point because a push_back can cause an internal buffer reallocation of the vector and that in turn invalidates all iterators.

    You should be using vector but if you are going to use any library class then read the documentation first http://www.cplusplus.com/reference/stl/vector/

    Comment

    Working...