Why are parentheses required to dereference a string iterator?

vector<string> MyStrings; vector<string>::iterator ItStr; 

I use c_str () to return a pointer to a string.

Why is it necessary to dereference with parentheses?

Does not compile: *ItStr.c_str();

error C2039: 'c_str': not a member of 'std :: vector <_Ty> :: iterator'

Compiles / works with parentheses around an iterator: (*ItStr).c_str();

If you could point me (not a pun) in the right direction, I would appreciate it. Thanks!

+4
source share
4 answers

. has a higher priority than unary * .

*ItStr.c_str() looks like you said *(ItStr.c_str()) .

You can, of course, just use ItStr->c_str() , since (*x).y equivalent to x->y (at least for pointers and iterators, you can, of course, overload the operators for your own types so that they were incompatible, but you would be crazy to do this).

+12
source

Because the operator . takes precedence over the * operator. See this link

+5
source

Without brackets *ItStr.c_str(); interpreted as:

 *(ItStr.c_str()); 

which is obviously wrong and which you might not have intended. It is interpreted in this way since the operator . has a higher priority than the * operator. To avoid this, you need to use brackets here:

 (*ItStr).c_str(); 

So that it can be interpreted correctly, the way you are going to interpret it.

Take a look:

+4
source

Without parentheses, you are trying to dereference the entire ItStr.c_str() operator.

Using parens around *ItStr you ItStr and then take its member .c_str() . The arrow operator -> can also be used instead of placing parentheses around dereferenced ItStr .

As James et al noted, this is the operator's priority issue.

+2
source

All Articles