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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With