iterators can't access problems properly

前端 未结 3 1676
攒了一身酷
攒了一身酷 2021-01-20 11:27

I am trying to access the element of a vector using the iterator. But I get strange outputs.

std::vector ivec{ 7, 6 , 8, 9} ; 

std::vector

        
相关标签:
3条回答
  • 2021-01-20 11:40

    end iterators are not iterators that you can de-reference. They point past the last element into the container. There's a good reason why this needs to be true; but long and short, the end iterator does not actually point to any element. If you want the last element, you need to decrement the end iterator.

    0 讨论(0)
  • 2021-01-20 11:45

    For your first example, std::vector<T>::end points to the theoretical element after the actual last element, so dereferencing it does not make sense. It is primarily used for checking when you have got past the end of the vector in a loop.

    For your second example, the results are as you would expect:

    cout << *(beg++) ; //increments beg after dereferencing
    cout << *(++beg) ;  //increments beg before dereferencing
    cout << *(beg+=1) ; //dereferences the result of adding one to beg
    
    0 讨论(0)
  • 2021-01-20 11:50

    As it is stated in here,

    Return iterator to end, Returns an iterator referring to the past-the-end element in the vector container.

    The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.

    Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with vector::begin to specify a range including all the elements in the container.

    If the container is empty, this function returns the same as vector::begin.

    0 讨论(0)
提交回复
热议问题