这就是我到目前为止所尝试的内容:
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
。有谁知道我在做错了什么?
答案 0 :(得分:4)
添加到向量时,可能会重新分配内部存储,这将使所有现有迭代器无效。对无效迭代器进行算术运算不会很好。
答案 1 :(得分:2)
向量的迭代器在重新分配时失效,当当前容量不足以容纳实际内容加上新添加的元素时,会发生这种情况。
这里最有可能发生的是current_
迭代器,它在构造时初始化,后来插入options_
会失效,这会在评估表达式时给出未定义的行为:
current_ - begin(options_)