我可以在 STL::vector::iterator 上进行指针算术吗

发布于 2024-08-23 04:53:35 字数 354 浏览 3 评论 0原文

目前,我使用迭代器来搜索向量并测试其元素。我使用以下方法访问元素:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

嘿看小鸭子会跑 2024-08-30 04:53:35

是的,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.

妥活 2024-08-30 04:53:35

这确实可以工作,因为向量迭代器是随机访问迭代器。这不仅可以像处理指针一样对它们进行操作,而且它们几乎是使用指针/指针算术来实现的。

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.

莫多说 2024-08-30 04:53:35

好吧,如果迭代器位于容器的最后一个元素上,则

*(it + 1) 

具有未定义的行为。
您应该

it + 1 != end

在取消引用之前检查它。

Well, if iterator is on the last element of the container then

*(it + 1) 

has undefined behavior.
You should check that

it + 1 != end

before dereferencing it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文