简体   繁体   English

获取std :: vector的索引 <std::string> ::迭代

[英]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 . 但是curr_opt_id()返回-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_迭代器会在随后插入options_时失效,这会在评估表达式时给您带来不确定的行为:

current_ - begin(options_)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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