Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does dereferencing a string vector iterator need parentheses?

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

I'm using c_str() to return the pointer to the string.

Why does it need to be dereferenced with parentheses?

Doesn't compile: *ItStr.c_str();

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

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

If you could point me (no pun intended) in the right direction I would appreciate it.Thanks!

like image 461
T.T.T. Avatar asked Nov 29 '22 18:11

T.T.T.


2 Answers

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

like image 22
Chad Avatar answered May 19 '23 19:05

Chad


. has higher precedence than the unary *.

*ItStr.c_str() is as if you had said *(ItStr.c_str()).

You can, of course, just use ItStr->c_str(), since (*x).y is equivalent to x->y (at least for pointers and iterators; you can, of course, overload the operators for your own types such that they are not consistent, but you'd be crazy to do so).

like image 53
James McNellis Avatar answered May 19 '23 17:05

James McNellis