We help IT Professionals succeed at work.
Get Started

case insensitive std::string comparison in std::map

vanista
vanista asked
on
7,671 Views
Last Modified: 2010-04-21
I needed a clever and efficient way to do a case insensitive comparison of std::string keys in a std::map. The map is used to match a string to an enum value. I wanted the keys to preserve their case and keep the basic functionnality of the map for search without having to convert to lower case.

My solution was to write a custom std::__less function for the map which uses strcasecmp. It works amazingly well. I'm wondering though if there could be portability issues with this solution? .. The code would have to be linux and windows compatible preferably.


#include <string.h>
#include <string>
#include <map>
 
struct __lesscasecmp
{
   bool operator() (const std::string& a, const std::string& b) const
   {
      return (strcasecmp (a.c_str ( ), b.c_str ( )) < 0);
   }
};
 
 
typedef std::map<std::string, int, __lesscasecmp>  tCmdMap;

Open in new window

Comment
Watch Question
Senior Software Engineer (Avast)
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 15 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE