简体   繁体   中英

Getting index of a std::vector<std::string>::iterator

So that's what I have tried so far:

class menu_item
{
  private:

    // ....

    std::vector<std::string> options_;
    std::vector<std::string>::iterator current_;

  public:
    menu_item(std::string name, std::vector<std::string> options)
        : name_(name), options_(options)
    {
        current_ = begin(options_);
    }

    // ....

    const int curr_opt_id()
    {
        return current_ - begin(options_);
    }
};

But curr_opt_id() returns -24 . Does anybody know what I am doing wrong here?

When you add to a vector, there's a chance that the internal storage will be reallocated which will invalidate all existing iterators. Doing arithmetic on an invalid iterator isn't going to end well.

See Iterator invalidation rules

Iterators of a vector get invalidated upon reallocation, which happens when the current capacity is not sufficient to hold the actual content plus a newly added element.

What is most likely happening here is that the current_ iterator, which is initialized at construction time, gets invalidated by subsequent insertions into options_ , which gives you undefined behavior when evaluating the expression:

current_ - begin(options_)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM