vector<int> v = { 1,2,3 }; for (auto b = v.begin(); b != v.end(); ++b) cout << *b << endl;
C++的迭代器的end()为什么指向最后元素的下一个位置,然后用!=运算符判断,而不是指向最后一个元素,用==运算符判断呢?
指向最后元素的下一个位置的话不能解引用,感觉不如直接指向最后元素方便啊。
认证0级讲师
If end is the last element, then begin must be the leading element of the first element, just like java. Otherwise, what will you do if you leave the container empty?
It’s just that C++ adopts the design style of trailing elements.
If the iterator is designed so that end() points to the last element, how should the iteration be written?
for (auto b = v.begin(); ; ++b) { cout << * b << endl; if(b == v.end()) break; }
Is this elegant? And if v is empty, judgment logic must be added.
Asymmetry is more convenient for general purpose implementation, and Asymmetry is clearer when used for binary search.
If it points to the last element, then the expression will be false resulting in the last element not being traversed by such a loop.
What should I do if it points to the last element and uses the iterator to loop through or process the last element.
If end is the last element, then begin must be the leading element of the first element, just like java. Otherwise, what will you do if you leave the container empty?
It’s just that C++ adopts the design style of trailing elements.
If the iterator is designed so that end() points to the last element, how should the iteration be written?
Is this elegant? And if v is empty, judgment logic must be added.
Asymmetry is more convenient for general purpose implementation, and
Asymmetry is clearer when used for binary search.
If it points to the last element, then the expression will be false
resulting in the last element not being traversed by such a loop.
What should I do if it points to the last element and uses the iterator to loop through or process the last element.