【发布时间】:2016-12-06 06:30:26
【问题描述】:
在Elements of Programming一书的第 91 页中,Stepanov 和 McJones 说 Iterator 的概念需要一个 successor 函数,但这不一定是常规的,因为
...
i = j并不意味着successor(i) = successor(j)...
(见page online)
我理解相反的successor(i) = successor(j) 并不暗示i=j(例如在两个以空结尾的列表中)并且可能没有为某些输入定义successor 函数。但我不明白i = j 怎么可能导致successor(i) != successor(j)。
他们指的是什么情况?也许是一些随机(如偶然)跳跃的迭代器?或者一些具有隐藏状态的迭代器,在指向同一个元素(并且在这个意义上比较相等)之后,与另一个迭代器“跳跃”不同。
他们立即跳转到需要常规 successor 函数的改进(ForwardIterator),所以我不清楚。
最初我认为输入迭代器可以具有此属性。但是,我仍然很难看出这是否构成反例:(在 STL 的某个实现中)。
#include <iostream>
#include <sstream>
#include <iterator>
#include <numeric>
#include <cassert>
using std::cout; using std::endl;
int main(){
std::istream_iterator<int> it1(std::cin); // wait for one input
std::istream_iterator<int> it2 = it1;
assert(it1 == it2);
cout << "*it1 = " << *it1 << endl;
cout << "*it2 = " << *it2 << endl;
cout << "now sucessor" << endl;
++it1; // wait for one input
++it2; // wait for another input
assert(it1 == it2); // inputs still compare equal !
cout << "*it1 = " << *it1 << endl;
cout << "*it2 = " << *it2 << endl;
assert(it1 == it2); // also here ! and yet they point to different values...
assert(*it1 == *it2); // assert fails!
}
(使用 GCC 6.1 编译)
【问题讨论】:
标签: c++ iterator regular-type