Hackerrank Day 8: Dictionaries and Maps solution in C++ This is a solution for the Day 8 hackerrank.com challenge. The basic idea of the challenge is to create a mapping of names to phone numbers based on the the given input, and later look up the phone numbers for certain names. If the entry exists, print it and its number. If it doesn't, print out "Not found".

Here's my solution in C++:

#include&lt;iostream&gt;
#include&lt;map&gt;
using namespace std;
int main()
{
    int i, n;
    cin&gt;&gt;n;
    string name, number, key;
    map&lt;string, string&gt; phone_dir;
    for(i=0; i&lt;n; i++)
    {
        cin&gt;&gt;name&gt;&gt;number;
        phone_dir.insert(pair &lt;string, string&gt; (name, number));
    }
    while(cin&gt;&gt;key)
    {
        if (phone_dir.find(key) != phone_dir.end())
        {
             cout&lt;&lt;key&lt;&lt;"="&lt;&lt;phone_dir.find(key)-&gt;second&lt;&lt; endl;
        }
        else cout&lt;&lt; "Not found"&lt;&lt;endl;
    }

    return 0;

}


Is there a more efficient solution in C++ for this problem?
You should not use using namespace std; This is bad practice that will get you into trouble once you want to use a function that has the same name.
You can use descriptive names. So instead of "n" use "numEntries" or whatever.
You should declare the iteration variable inside the for loop rather than at the beginning.
std::map has an emplace method that you should use rather than insert.
You are using a std::map, which is is a red black tree. You most likely want a std::unordered_map
You search twice for the key. With modern C++17 you can do the following:

if (auto res = phone_dir.find(key); res != phone_dir.end())
{
     std::cout &lt;&lt; key &lt;&lt; "=" &lt;&lt; res-&gt;second &lt;&lt; std::endl;
} else {
     std::cout &lt;&lt; "Not found" &lt;&lt; std::endl;
}

You are using std::endl which involves a flush of the stream. You definitely only want a \n here.
Whitespace is cheap. Grab some to improve readability
Same for lines. It is bad practice to have braces on one condition and pu the other one on the same line. This severely affects readability
return 0; is implied for main so you can skip that.
I almost forgot, you should reserve the space in the map.