search

Home  >  Q&A  >  body text

C++迭代器的尾指针为什么不指向最后一个元素?

vector<int> v = { 1,2,3 };
for (auto b = v.begin(); b != v.end(); ++b)
    cout << *b << endl;

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

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

PHP中文网PHP中文网2803 days ago549

reply all(5)I'll reply

  • 巴扎黑

    巴扎黑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.

    reply
    0
  • PHP中文网

    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.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:04:24

    Asymmetry is more convenient for general purpose implementation, and
    Asymmetry is clearer when used for binary search.

    reply
    0
  • 怪我咯

    怪我咯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.

    reply
    0
  • 天蓬老师

    天蓬老师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.

    reply
    0
  • Cancelreply