Home > Software design >  How to make std::map::find function case sensitive?
How to make std::map::find function case sensitive?

Time:09-22

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

CodePudding user response:

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.

CodePudding user response:

What's happening here is that it's finding "TEST", then you're iterating through the remainder of the map, and printing out everything that came after that.

As it happens, in most common character sets, upper case letters sort before lower case letters, so TEST is going to be the first item in the map. So when you print things out starting from there, you end up printing out all the items.

But a map can only hold one item with a particular key, so there's no real reason to iterate. You either found the one item (it != container.end()) or you didn't (it == container.end()).

If you were using a multimap, there could be multiple items with the same key. In that case, you'd typically want to use std::equal_range to find all the items with that one key. That'll return a pair of iterators, one to the start of the range, and the other one past the end of the range of items with that key. You'd then print out all the items in the range it returned.

  • Related