gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:39:34 29 4
gpt4 key购买 nike

我一直认为“单一”迭代器是默认初始化的迭代器,它们可以作为各种可比较的哨兵值:

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;
}
}

但是this answer不仅表明我对“单数”的定义是错误的,而且我上面的比较也是完全不合法的。

是吗?

最佳答案

显然这对一些 迭代器有效——T* 是一个明显的例子——但绝对不能保证所有 迭代器的正确行为。 C++11 24.2.1 [iterator.requirements.general] p5:

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 标志复制您想要的行为:

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;
}
}

关于c++ - 这是一个单数迭代器吗?如果是,我可以将它与另一个迭代器进行比较吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17198239/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com