没有对您请求的支持 - 但您可以编写自己的even_only
and odd_only
实施。
基本思想是环绕相关容器的普通迭代器,并在每次外部增量一次时在内部进行双增量:
template <typename C, bool IsOdd>
class even_odd_only
{
C& c;
public:
class iterator
{
public:
// all the definitions required for iterator!
// most if not all might simply be derived from C::iterator...
// copy/move constructor/assignment as needed
// core of the wrapper: increment twice internally!
// just doing += 2 is dangerous, though, we might increment beyond
// the end iterator (undefined behaviour!)additionally, += 2 only
// is possible for random access iterators (so we limit usability)
void operator++() { ++b; if(b != e) ++b; }
// operator* and operator-> (both return *b), post-increment
// (defined in terms of pre-increment), etc...
// comparison: only needs to compare b iterators!
private:
C::iterator b;
C::iterator e; // needed for comparison to avoid incrementing beyond!
iterator(C::iterator b, C::iterator e) : b(b), e(e) { }
};
// const_iterator, too; possibly make a template of above
// and derive const and non-const iterators from?
even_odd_only(C& c) : c(c) { }
iterator begin()
{
using std::begin;
using std::end;
using std::empty;
auto b = begin(c);
// should be self-explanatory:
// skip first element in odd variant (if there is)
if constexpr(IsOdd) { if(!empty(c)) { ++b; } }
return iterator(b, end(c));
};
iterator end()
{
using std::end;
return iterator(end(c), end(c));
}
};
template <typename T>
using even_only = even_odd_base<T, false>;
template <typename T>
using odd_only = even_odd_base<T, true>;
事实上,它甚至可以与非随机访问甚至非双向迭代器一起工作。但特别是对于 RA 迭代器,它的效率低于经典循环(由于中间 if inoperator++
).
定义比较迭代器:始终operator==
and operator!=
,仅对于随机访问运算符,您还可以有operator[<|>|<=|>=]
(→ std::enable_if
).
您将找到有关如何编写迭代器的更多详细信息here https://stackoverflow.com/questions/3582608/how-to-correctly-implement-custom-iterators-and-const-iterators– 不过,当你遇到这种情况时,请记住std::iterator
本身现在已被弃用。