Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make stl::map key case insensitive [duplicate]

Tags:

c++

map

I am new to stl's. Here is my below program.

typedef pair<string, int> p;
int main(int argc, char *argv[])
{
  map<string,int> st;
  st.insert(p("hello",1));   //Inserted "hello" as key to map.
  st.insert(p("HELLO",1));   //Inserted "HELLO" as key to map. 
  cout<<"size="<<st.size()<<endl;    //Output is 2 because two records found "hello" and "HELLO"
  return 0;
}

I don't want to take account of the repeated case changes(upper case to lower case words or vice-versa). Here "st.insert(p("HELLO",1));" should fail, hence the no. of records should be "1" instead of "2". Is there any flag setup or like so?

I was unable to find the related questions hence posted this question.

Any help is thankful.

like image 853
Santosh Sahu Avatar asked Sep 30 '13 19:09

Santosh Sahu


People also ask

Is std::map find case sensitive?

If you use the standard std::map associative container with std::string or std::wstring as key types, you get a case sensitive comparison by default.

Can a std::map have duplicate keys?

STL map does not allow same Keys to be used. You may want to go for multi-map for that. Show activity on this post. a map will not throw any compile/run time error while inserting value using duplicate key.

Can there be duplicate keys in map C++?

Multi-map in C++ is an associative container like map. It internally store elements in key value pair. But unlike map which store only unique keys, multimap can have duplicate keys.


1 Answers

Use a custom comparator:

struct comp { 
    bool operator() (const std::string& lhs, const std::string& rhs) const {
        return stricmp(lhs.c_str(), rhs.c_str()) < 0;
    }
};

std::map<std::string, int, comp> st;

Edit : If you're not able to use stricmp or strcasecmp use :

#include<algorithm>
//...
string tolower(string s) {
    std::transform(s.begin(), s.end(), s.begin(), ::tolower );
    return s;
}
struct comp { 
    bool operator() (const std::string& lhs, const std::string& rhs) const {
        return  tolower(lhs) < tolower(rhs);
    }
};

std::map<std::string, int, comp> st;
like image 153
P0W Avatar answered Nov 12 '22 16:11

P0W