简体   繁体   English

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

[英]Can I do pointer arithmetic on an STL::vector::iterator

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? 我可以通过使用指针来达到预期效果吗?

Yes, the iterators for std::vector are random access iterators so you add/subtract integral values to get other valid iterators. 是的, std::vector的迭代器是随机访问迭代器,因此您可以添加/减去整数值以获得其他有效的迭代器。

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 好吧,如果迭代器位于容器的最后一个元素上,

*(it + 1) 

has undefined behavior. 具有未定义的行为。 You should check that 你应该检查一下

it + 1 != end

before dereferencing it. 在取消引用之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM