c++ empty std::vector begin not equals to end

前端 未结 3 1810
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 16:33

Hi I have situation on windows 10, that declared empty class member variable vector, but this vector\'s begin()(first iterator) and end()(last iterator)

相关标签:
3条回答
  • 2021-01-29 17:21

    The standard only requires that the iterators are equal, not that their adresses are the same. Considering the adresses of iterators is pointless.

    As other have stated, the two iterators are different objects, so they need to have different adresses.

    For reference, see this answer.

    0 讨论(0)
  • 2021-01-29 17:26

    The iterators are returned by value, so the address will indeed not be the same. Even if you do:

    const vector<whatever>::iterator &it1 = vect.begin();
    const vector<whatever>::iterator &it2 = vect.begin();
    

    the addresses of it1 and it2 can be different (and will be in many implementations) - even if references are used.

    (note that using begin() in both is not a mistake - the same method begin() will return two different objects with different values)

    0 讨论(0)
  • 2021-01-29 17:28
    std::vector<int> v;
    assert(v.begin() == v.end());
    

    This should work: begin and end compare equal.

    On the other hand

    auto b = v.begin();
    auto e = v.end();
    assert(&b == &e);
    

    is prohibited from working: the two iterators are different objects and must have different addresses.

    Compare the equivalent:

    int i = 42;
    int j = 42;
    assert(i == j);   // ok
    assert(&i == &j); // fail
    
    0 讨论(0)
提交回复
热议问题