Home > database >  Dereferencing Iterator
Dereferencing Iterator

Time:09-20

#include <iostream>
#include<string>
using std::string;
using namespace std;


int main()
{
    string s("some string");
    
    
      *s.begin() = toupper(*s.begin());
      
   
      std::cout << s << std::endl;
      
}

And the result is:

Some string

Why *s.begin() have to be used ? Why I cannot just use s.begin() ? like:

s.begin() = toupper(s.begin());

Why the dereferencing operator * have to be used infront of an iterator ?

In the book C prime FIFTH EDITION P.107 , it said we dereference that iterator to pass that character to toupper and to return the upper letter S to the original string.

But still I don't get it, why we cannot use the s.begin() directly. Isn't pointer just to save memory ?

CodePudding user response:

Suppose you'd be using a pointer:

 string s("some string");
 auto ptr = s.data();     // pointer to first character

Then you still need to dereference it before you can assign a character:

 *ptr = 'X';

Pointers add a level of indirection. A pointer is not the thing it points to. You have to dereference a pointer to access the pointee. With respect to that iterators are the same. An iterator into a string is not the character, though you can access the character via the iterator.

CodePudding user response:

If you read the documentation about std::string you can see the prototype of begin() which is iterator begin(), it returns an iterator.

The prototype of toupper() is int toupper ( int c );. It returns an int and accepts an int

Here you are tyring to assign an int (returned from toupper()) to an iterator (returned from s.begin()). And you are passing an iterator to toupper() which accepts an int.

s.begin() = toupper(s.begin()); // iterator = int(iterator)

If you dereference the iterator it will return the reference of the value it points to. (char&)

*s.begin() = toupper(*s.begin()); // int = int(int)

Keep in mind that you are using references with iterators and not pointer directly.

CodePudding user response:

An iterator is a pointer that helps looping trough an object. In this case s.begin() is a pointer, so in order to access it's value you have to dereference it with "*".

CodePudding user response:

s.begin() returns a pointer, to the first character in the string. If you want to assign a value to the memory pointed to, by the pointer, you need to dereference (*) it.

  •  Tags:  
  • c
  • Related