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.

Introduction

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

So here's my attempt to solve the questions provided in Cracking the Coding Interview in C++/C.

The idea came up because I wanted to become better at C++/C instead of learning Java all over again, so I was fairly disappointed that all the solutions were provided in Java.

Then I thought, there might be other readers who'd love a C implementation of the solutions provided in the book.

So this blog is dedicated to anyone who wants the solutions provided in C.

After I complete each section, I'll come back and write a post on it rather than giving a post on each question because come on, lets be honest. Nobody wants to read pages of a solution to a single question if it can be explained easily.

Note : This isn't perfect.

I just wrote code to how I perceived the question.

I first read the question and thought on how to solve it.

Next I read the algorithm and tips provided to see if there was a better solution.

Then I closed the book and tried to implement the algorithm in C++.

(No, I didn't look at the code they provided unless I was absolutely stuck).

You can get the code on github: https://github.com/prasanthlouis/C-equivalent-to-Cracking-the-Coding-Interview