仅在基于范围的循环中迭代奇数(偶数)元素
问题描述
Suppose we have a plain array (or other container which supports range-based loops):
Using indexes or iterators, we can loop over odd elements and increment the index by two:
How can I get a similar result by using a range-based loop and avoiding explicit iterators/indexes and iteration skipping? Something like this:
What does a simple and elegant solution look like? Does the standard library contain something like this?
There's no support for what you request – but you might write your own even_only
and odd_only
implementations.
Basic idea is to wrap around the normal iterator of the container in question and do a double increment internally each time we increment once externally:
As is, it would work even with non-random-access and even non-bidirectional iterators. But especially for RA-iterators, it's less efficient than the classic loop (due to the intermediate if in operator++
).
Defining comparison iterators: always operator==
and operator!=
, only for random access operators you can additionally have operator[<|>|<=|>=]
(→ std::enable_if
).
You'll find more details about how to write an iterator here – keep in mind when you encounter, though, that std::iterator
itself is deprecated now.
这篇关于仅在基于范围的循环中迭代奇数(偶数)元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!