Search code examples
c++c++11findstdmapstd

How to make std::map::find function case sensitive?


I had interviewed with a MNC company. He gave me the following code and asked me to make find() function as case-sensitive. I tried, but failed to understand how to make inbuilt find function as case-sensitive. Is there any way to make it case-sensitive to find only a particular key value?

#include <iostream>
#include <map>
using namespace std;

int main()
{
    map<string, int> mp;
    mp["Test"] = 1;
    mp["test"] = 2;
    mp["TEST"] = 3;
    mp["tesT"] = 4;    

    for (auto it = mp.find("TEST"); it != mp.end(); it++)
    {
        cout << it->first << " " << it->second << endl;
    }

    return 0;
}

Output :

TEST 3
Test 1
tesT 4
test 2

But I expect output is:

TEST 3

Solution

  • The problem is the for loop. You do not need to iterate through the map to print it. Rather you need to do

    auto it = mp.find("TEST");
    if (it != mp.end())
        std::cout << it->first << " " << it->second << std::endl;
    

    The std::map::find will find an iterator pointing to the key-value pair which has key exactly "TEST", if not found just the end iterator.