Translate this for me, thanks [map cout]

So i have a map function an was looking over the internet for ways to print out my content from the map and found this quite simple looking for-loop, thats works as a charm.But i cant for the life of me "translate" it in my head so i understand it. So if someone can do some psuedo-translation for me explaning the code i would be happy. Thanks

1
2
  for (map<string, int>::iterator it=words.begin(); it!=words.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';


I am afraid there is not much to translate. The code uses just an ordinary iterator to loop through all the elements of a map and print them to the console.

http://www.cplusplus.com/reference/iterator/
http://www.cprogramming.com/tutorial/stl/iterators.html
You left out a key piece of information, which is the definition of words.
However, we can deduce from your snippet that words looks like:
1
2
 
  map<string,int>   words;


It might be a little clearer if we define the iterator outside the for statement:
1
2
 
  map<string,int>::iterator it;  // Define an iterator for the map 


Now, the for statement looks a little simpler.
 
  for (it=words.begin(); it!=words.end(); ++it)

This is a vanilla for loop using an iterator. begin() returns an iterator pointing to the first element in the map. end() returns an iterator pointing past the end of the map. ++it increments the iterator for each iteration of the for loop.

A map iterator is a std::pair<const key_type, mapped_type>.
http://www.cplusplus.com/reference/utility/pair/
So we can simply use it->first and it->second to reference the string and int values in the cout statement.

maps are not stored as arrays, but it can be helpful to think of your map as an array. Your iterator starts by pointing at the first element. Each time you increment the iterator, you point to the next element until you reach the end.

Last edited on
Aaah!!

Thanks finally i understand it. I was going crazy looking at it i think it was defining the iterator that made be so confused about it.

- Zorac
Topic archived. No new replies allowed.