C++迭代器的尾指针为什么不指向最后一个元素?
PHP中文网
PHP中文网 2017-04-17 13:02:24
0
5
555
vector<int> v = { 1,2,3 };
for (auto b = v.begin(); b != v.end(); ++b)
    cout << *b << endl;

C++的迭代器的end()为什么指向最后元素的下一个位置,然后用!=运算符判断,
而不是指向最后一个元素,用==运算符判断呢?

指向最后元素的下一个位置的话不能解引用,感觉不如直接指向最后元素方便啊。

PHP中文网
PHP中文网

认证0级讲师

reply all(5)
巴扎黑

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.

Ty80

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.

Peter_Zhu

What should I do if it points to the last element and uses the iterator to loop through or process the last element.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template