这就是我到目前为止所尝试过的:
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 时,内部存储有可能会被重新分配,这将使所有现有的迭代器无效。对无效迭代器进行算术不会有好的结果。
关于c++ - 获取 std::vector<std::string>::iterator 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16362651/