Why do I need to dereference iterators?

后端 未结 3 1763
小蘑菇
小蘑菇 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);
    

提交回复
热议问题