Why do I need to dereference iterators?

后端 未结 3 1757
小蘑菇
小蘑菇 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:02

    Iterator is a generalized pointer. It points to something. If you have a function that needs that something(char or int, in this case), not the "pointer" itself, you need to dereference the iterator.

    For example, the standard advance function takes an iterator as its argument. Therefore you pass the iterator without dereferencing it, as in

    std::advance(it, n);
    

    But if you have an iterator that points to an int and you want to increment that integer by 4, you need

    (*it) += 4;
    

    I suggest that you should read a good book on C++.

    By the way, your entire loop can be replaced by a single call to transform

     std::transform(s.begin(), s.end(), s.begin(), toupper);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-29 09:16

    You need to be able to perform operations on the iterator itself e.g. your code does it != s.end() and ++it

    And sometimes you need to be able to perform operations on the object the iterator points to, e.g. isupper(*it)

    There has to be some operation to indicate you want to refer to the thing it refers to not the iterator itself, otherwise if you test if (it == another_it) how would the compiler know if you were trying to compare the iterators or the things they point to? The same applies to the ++it operation, which wants to modify the iterator, not the thing it points to.

    Iterators could have a get() member to return the thing they refer to, so you'd do isupper(it.get()) but instead they support the dereference operator, which is less typing and is consistent with pointers and allows pointers to be used in any code that expects iterators.

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