Why do I need to dereference iterators?

后端 未结 3 1796
小蘑菇
小蘑菇 2021-01-29 08:19

Why do I need to dereference iterators? For example in the following program

#include 
#include 
#include 

int main(         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-29 09:14

    In order to distinguish operations on pointer-to-T and operations on the subject T it is necessary to have a dereferencing operator.

    For example:

    int* x = ...;
    
    x++;
    

    Do you mean you want to increment the pointer so it is pointing to the next int in memory? Or do you want to increment the int pointed to by x?

    Without the deferenencing operator this would be ambiguous.

    Iterators are simply a generalization of the pointer interface.

    Contrast with references:

    int& x = ...;
    
    x++;
    

    References have the alternative semantic, and do not require dereferencing. An operation on reference-to-T applies to the subject T. The downside is that you can't modify the reference itself.

提交回复
热议问题