Lig*_*ica 9 c++ iterator std c++03
我一直认为"奇异"迭代器是一个默认初始化的迭代器,它们可以作为类似的哨兵值:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但这个答案不仅表明我对"单数"的定义是错误的,而且我上面的比较完全是非法的.
是吗?
显然这对一些迭代器起作用- 这T*是一个明显的例子 - 但绝对不能保证所有迭代器的正确行为.C++ 11 24.2.1 [iterator.requirements.general] p5:
奇异值与任何序列都没有关联...对于奇异值,大多数表达式的结果都是未定义的; 唯一的例外是破坏一个包含奇异值的迭代器,一个非奇异值赋值给一个包含奇异值的迭代器,对于满足DefaultConstructible要求的迭代器,使用一个值初始化的迭代器作为源复制或移动操作.
您可以使用简单的bool标志复制所需的行为:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
662 次 |
| 最近记录: |