Thursday, June 25, 2009

Secrets of std::map

I should admit that I'm very poor in C++ Programming. Today, me and one of colleague was trying to understand a code writter by one of a pioneer in our team. We initially thought he wrote a crabby code but indeed we were wrong and he proved his expertness :)

Below is the snippet of similar case.



#include "stdafx.h"
#include < iostream >
#include < map >

int main()
{
// 1. define the map
typedef std::map Map;

// 2. Create the object for it
Map myMap;

for (int i=0; i<10; ++i)
{
/****************************
3. Whats going on here ???.
We just created the object.
Could this be a buggy code ??

Nope. When we reference an item in map
and if the item is not available,
it creates the object. Great :)

I personally seen/used the creation
of map on the left side,
something like myMap[2] = 20
But the below is of something which
I am seeing new today :)
**********************************************/

int &ref = myMap[i];
ref = i;

}
for (int i=0; i<10; ++i)
{
std::cout << myMap[i] << " ";
}
std::cout << std::endl;

return 0;
}



Happy Hacking :)

No comments:

Post a Comment