[英]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.
在无效的迭代器上进行算术运算不会很好地结束。
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.