这是一个单一的迭代器,如果是,我可以将它与另一个迭代器进行比较吗?

Is this a singular iterator and, if so, can I compare it to another one?(这是一个单一的迭代器,如果是,我可以将它与另一个迭代器进行比较吗?)
本文介绍了这是一个单一的迭代器,如果是,我可以将它与另一个迭代器进行比较吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为单一"迭代器是一个已经默认初始化的迭代器,它们可以作为类似的 sentinel 值:

I always thought that a "singular" iterator was one that has been default-initialised, and these could serve as comparable sentinel values of sorts:

typedef std::vector<Elem>::iterator I;
I start = I();

std::vector<Elem> container = foo();

for (I it = container.begin(), end = container.end(); it != end; ++it) {
   if ((start == I()) && bar(it)) {
      // Does something only the first time bar(it) is satisfied

      // ...

      start = it;
   }
}

但是这个答案不仅表明我对单数"的定义是错误的,而且我上面的比较是完全违法.

But this answer suggests not only that my definition of "singular" is wrong, but also that my comparison above is totally illegal.

是吗?

推荐答案

显然这适用于 一些 迭代器 - T* 是一个明显的例子 - 但它绝对不是保证 all 迭代器的正确行为.C++11 24.2.1 [iterator.requirements.general] p5:

Obviously this will work for some iterators - T* being a clear example - but it's definitely not guaranteed correct behavior for all iterators. C++11 24.2.1 [iterator.requirements.general] p5:

奇异值不与任何序列相关联...大多数表达式的结果对于奇异值是未定义的;唯一的异常正在破坏包含奇异值的迭代器,将非奇异值分配给包含奇异值,并且,对于满足DefaultConstructible 要求,使用值初始化的迭代器作为复制或移动操作的来源.

Singular values are not associated with any sequence ... Results of most expressions are undefined for singular values; the only exceptions are destroying an iterator that holds a singular value, the assignment of a non-singular value to an iterator that holds a singular value, and, for iterators that satisfy the DefaultConstructible requirements, using a value-initialized iterator as the source of a copy or move operation.

您可以使用简单的 bool 标志复制您想要的行为:

You can replicate your desired behavior with a simple bool flag:

std::vector<Elem> container = foo();
bool did_it_already = false;

for (I it = container.begin(), end = container.end(); it != end; ++it) {
   if (!did_it_already && bar(it)) {
      // Does something only the first time bar(it) is satisfied

      // ...

      did_it_already = true;
   }
}

这篇关于这是一个单一的迭代器,如果是,我可以将它与另一个迭代器进行比较吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)