vector<int> v = { 1,2,3 };
for (auto b = v.begin(); b != v.end(); ++b)
cout << *b << endl;
C++的迭代器的end()为什么指向最后元素的下一个位置,然后用!=运算符判断,
而不是指向最后一个元素,用==运算符判断呢?
指向最后元素的下一个位置的话不能解引用,感觉不如直接指向最后元素方便啊。
巴扎黑2017-04-17 13:04:24
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.
PHP中文网2017-04-17 13:04:24
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.
大家讲道理2017-04-17 13:04:24
Asymmetry is more convenient for general purpose implementation, and
Asymmetry is clearer when used for binary search.
怪我咯2017-04-17 13:04:24
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.
天蓬老师2017-04-17 13:04:24
What should I do if it points to the last element and uses the iterator to loop through or process the last element.