Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive std::set of strings

Tags:

How do you have a case insensitive insertion Or search of a string in std::set?

For example-

std::set<std::string> s; s.insert("Hello"); s.insert("HELLO"); //not allowed, string already exists. 
like image 907
cpx Avatar asked Nov 27 '10 11:11

cpx


People also ask

Is string comparison case sensitive in C++?

String comparison is case sensitive by default. Just use operator== for std::string .

What is case insensitive string comparison?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function.


2 Answers

You need to define a custom comparator:

struct InsensitiveCompare {      bool operator() (const std::string& a, const std::string& b) const {         return strcasecmp(a.c_str(), b.c_str()) < 0;     } };  std::set<std::string, InsensitiveCompare> s; 

You may try stricmp or strcoll if strcasecmp is not available.

like image 199
Yakov Galka Avatar answered Oct 14 '22 11:10

Yakov Galka


std::set offers the possibility of providing your own comparer (as do most std containers). You can then perform any type of comparison you like. Full example is available here

like image 25
John Sloper Avatar answered Oct 14 '22 09:10

John Sloper