This is my first post on the C++ forums. I'm fairly new to C++ (started coding in the language about a month ago). I'm coming from a significant amount of AS3 and most standard web languages as well as some C#. Still trying to get the grasp of the logic behind the language and have come across this inquiry:
Using this code (referenced from a game programming tutorial):
std::map<std::string, CEntityManager*>::iterator it = _mEntity.find(name);
I'm confused not by what it is doing but the rather wordy length to accomplish a map iteration.
I have a member variable "_mEntity", is it not possible to do this (and I realize this might seem obscure): _mEntity::iterator it;
My logic is that since "_mEntity" is a map, why/how does referencing std::map iterator recognize what map to iterate through?
Another example (taken off this webpage):
map<char,int> mymap;
map<char,int>::iterator it;
Again, how does this setup know to iterate through "mymap". Sorry if this seems rudimentary , but I would appreciate a better understanding of this.
The standard library iterators have a state in which they save the information about the container they are iterating through. So when you call _mEntity.find(name) the iterator object which is returned knows on which container to operate (namely, _mEntity).
In your second example, the iterator it doesn't know that it will be iterating over mymap yet - no connection between those two is established before you call something like mymap.find() or mymap.begin() or any other function returning an iterator. So basically you can do something like this:
1 2 3 4 5 6 7 8
map<char,int> mymap1;
map<char,int> mymap2;
map<char,int>::iterator it;
it = mymap1.begin(); // it works on mymap1
it = mymap.find('a'); // now, it works on mymap2
Hope this clears up a bit on what is going on inside the iterators (of course, as usual, for even deeper understanding - try Googling :) Perhaps this is a good introduction http://www.cprogramming.com/tutorial/stl/iterators.html ).
As for lengthy declarations of iterator variables - it has been greatly simplified in C++11 standard with introduction of the auto keyword, which deduces the type of variable from its initialization:
auto it = _mEntity.find(name); // Same as your first example
If you have more questions - don't hesitate to ask. Cheers.
Thank you for the detailed (and very timely) response!
I did google a bit before I posted to see if I could get a better understanding, I've bookmarked that site link you posted as I don't believe my searches were very well organized, and that site in particular looks promising.
That cleared everything up for me, makes perfect sense. auto looks very useful.