iterators can't access problems properly

前端 未结 3 1681
攒了一身酷
攒了一身酷 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:45

    For your first example, std::vector::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
    

提交回复
热议问题