我可以在 STL::vector::iterator 上进行指针算术吗
目前,我使用迭代器来搜索向量并测试其元素。我使用以下方法访问元素:
std::vector<int>::iterator it;
if (*it == 0);
我可以使用相同的指针算术样式逻辑来测试下一个元素(而不改变我的迭代器)吗?
我首先需要看看它是否会将迭代器推出界限
if (it != myvec.end())
然后测试当前元素和下一个元素
if (*it == 1 && *(it + 1) == 1)
这会像我期望的那样使用指针吗?
Currently I use an iterator to search through a vector and test its elements. I access the elements using
std::vector<int>::iterator it;
if (*it == 0);
Can I use the same pointer arithmetic style logic to also test the next element (without altering my iterator)?
I first need to see if it will push the iterator out of bounds
if (it != myvec.end())
Then test both current element and next element
if (*it == 1 && *(it + 1) == 1)
Will this work as I expect from using pointers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,
std::vector
的迭代器是随机访问迭代器< /a> 因此您可以添加/减去整数值以获得其他有效的迭代器。从技术上讲,它可能不是指针算术,但它们的作用就像指针一样。
Yes, the iterators for
std::vector
are random access iterators so you add/subtract integral values to get other valid iterators.Technically, it may not be pointer arithmetic, but they act just like pointers.
这确实可以工作,因为向量迭代器是随机访问迭代器。这不仅可以像处理指针一样对它们进行操作,而且它们几乎是使用指针/指针算术来实现的。
This will work indeed as vector iterator are random access iterator. That is not only can you act on them like you would do with pointers, but they are pretty much implemented using pointers / pointer arithmetic.
好吧,如果迭代器位于容器的最后一个元素上,则
具有未定义的行为。
您应该
在取消引用之前检查它。
Well, if iterator is on the last element of the container then
has undefined behavior.
You should check that
before dereferencing it.