2

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?

ole
  • 5,166
  • 5
  • 29
  • 57

2 Answers2

3

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

Community
  • 1
  • 1
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
2

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_)
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451