Thursday, 9 July 2015

Maps

https://github.com/prasanthlouis/C-equivalent-to-Cracking-the-Coding-Interview

So I've worked with maps and vectors in other languages. But never in C++.

It troubled me at first, because it wouldn't compile at first. I later realized that I had to use C++ 11 (facepalm!).

My code:


unordered_map<string,int> mymap={{"prasanth",21},{"nelson",19}};
mymap.insert({"louis",54});
for(auto& x: mymap)
cout<<x.first<<"-"<<x.second<<endl;
cout<<mymap.at("louis");


Nothing to complex here. You have your keyword followed by your data types within angle brackets (i.e your key data type and your data data type). This is followed by your keys and data values within curly braces.

If you want to enter values into your map use the .insert() method, with your key and data value inside.

Here was something I didn't really understand the first time.

'auto& x:mymap'

Lets break this down.

The colon means "a range", x will iterate inside every element inside the map 'mymap'.

Now auto&

Auto means that the variable that it is being assigned to will take the type according to its initializer.

Eg. auto a=3+4

and if you decided to print the type a, it'll be an integer (Since int+int=int).

Now &. & is used for a reference. So use auto& if you want to work with the original variables and modify them.

Now to print the key out use the keyword .first and the print out the values use .second.

You can access a value by it's key by  using .at.

No comments:

Post a Comment