c++ - 获取 std::vector<std::string>::iterator 的索引

标签 c++ string vector stl iterator

这就是我到目前为止所尝试过的:

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_);
    }
};

但是curr_opt_id()返回-24。有人知道我在这里做错了什么吗?

最佳答案

当您添加到 vector 时,内部存储有可能会被重新分配,这将使所有现有的迭代器无效。对无效迭代器进行算术不会有好的结果。

参见Iterator invalidation rules

关于c++ - 获取 std::vector<std::string>::iterator 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16362651/

相关文章:

c++ - 我如何在二维字符 vector 中查找和替换字符? C++

c++ - 如何在结构或类的 vector 中快速搜索具有特定值的对象? C++

c++ - 在 DLL 中使用的最简单的 C++ PUSH 通知/POST 解决方案?

c++ - 自定义类型需要一个初始化程序来声明自动?

c++ - 错误 C2661 : 'CObject::operator new' : no overloaded function takes 4 arguments

java - 从 Java 中的文件中读取行

python - 将字符串拆分为两个单独的数字和字母列表 -python

c++ - 获取字体列表 (Win32)

c - 使用 C 实现哈希表

c++ - 删除两个相邻元素并用 vector 中的单个元素替换它们