Is it possible to overload operator== for const char* so that the actual C string and not the pointer values would be used to determine if the map elements are equal

No it's not, and yes, it's not a good idea for exactly the reason pointed out in the question and because you don't need char*, you can use a std::string instead. (you can provide a custom compare function - as pointed out by simonc, but I'd advise against it)

//Could these be referring to different map elements?
int i = imap["hello"];
int j = imap["hello"];

Yes, and they can even refer to elements that don't exist yet, but they'll be created by operator[] and be value initialized. The same issue exists with assignment:

imap["hello"] = 0;
imap["hello"] = 1;

The map could now have 1 or 2 elements.

Answer from Luchian Grigore on Stack Overflow
🌐
O'Reilly
oreilly.com › library › view › c-cookbook › 0596007612 › ch06s07.html
6.6. Mapping strings to Other Things - C++ Cookbook [Book]
November 8, 2005 - #include <iostream> #include <map> #include <string> using namespace std; int main() { map<string, string> strMap; strMap["Monday"] = "Montag"; strMap["Tuesday"] = "Dienstag"; strMap["Wednesday"] = "Mittwoch"; strMap["Thursday"] = "Donnerstag"; strMap["Friday"] = "Freitag"; strMap["Saturday"] = "Samstag"; // strMap.insert(make_pair("Sunday", "Sonntag")); strMap.insert(pair<string, string>("Sunday", "Sonntag")); for (map<string, string>::iterator p = strMap.begin(); p != strMap.end(); ++p ) { cout << "English: " << p->first << ", German: " << p->second << endl; } cout << endl; strMap.erase(strMap.find("Tuesday")); for (map<string, string>::iterator p = strMap.begin(); p != strMap.end(); ++p ) { cout << "English: " << p->first << ", German: " << p->second << endl; } }
Authors: D. Ryan StephensChristopher DigginsJonathan TurkanisJeff Cogswell
Published: 2005
Pages: 594
Discussions

Make std::map find a std::string key using a char* without converting it to a std::string.
Do you have performance issues with char* to string conversion? If no - it is safest way to deal with this datatype mix… More on reddit.com
🌐 r/Cplusplus
9
2
August 20, 2021
Map to String - C++ Forum
So I am given the function where I am given a map that has a string key and a long value, and it is a pointer of m. I know how to print a map, but I am not sure on how to go about for taking the map and making it into a single string. It should be printed as string:long, comma separting the ... More on cplusplus.com
🌐 cplusplus.com
March 19, 2017
performance - how to best achieve string to number mapping in a c program - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... List is of 30 such strings and their number mapping. More on stackoverflow.com
🌐 stackoverflow.com
C Map String to Function - Stack Overflow
So, I'm making a Unix minishell, and have come to a roadblock. I need to be able to execute built-in functions, so I made a function: int exec_if_built_in(char **args) It takes an array of strings... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/cplusplus › make std::map find a std::string key using a char* without converting it to a std::string.
r/Cplusplus on Reddit: Make std::map find a std::string key using a char* without converting it to a std::string.
August 20, 2021 -

I have a map that has std::string's as its key type, and i'll need to find elements in this map using strings that are passed to me as char* . Normally find() would automatically convert my char* string to an std::string before searching, but is there a way to make it compare the std::string keys to char* strings using std::string::c_str() and strcmp() ? (i can't change the data types here, i really need to use std::stringfor the key.)

🌐
Cplusplus
cplusplus.com › forum › general › 211386
Map to String - C++ Forum
March 19, 2017 - So I am given the function where ... for taking the map and making it into a single string. It should be printed as string:long, comma separting the elements with no comma at the end....
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 44190-table-mapping-strings-strings.html
Table mapping Strings to Strings
September 3, 2003 - typedef struct Entry { char *pName; char *pDescription; } Entry; Entry Table[100]; Table[0].pName = pAName; Table[0].pDescription = pADescription; But it's your choice...
Find elsewhere
Starred by 536 users
Forked by 209 users
Languages: C
Top answer
1 of 3
4

You cannot avoid this. There are more possible strings than integers, therefore hash collisions are imminent. Read up on hashmaps - it's a data structure that explicitly takes collisions into account and works around them.

2 of 3
2

A map data structure and "collision" cannot be separated. the way you started your implementation seems fine, here's how you should handle collisions :

Adding a new entry into the map

  1. calculate hashcode for key
  2. compute index from hashcode (more or less index = hashcode value % size of keyset)
  3. if keyset[index] is not null
    1. if keyset[index] != key (ie. for strings, use strcmp) increment index modulus size of keyset, then goto 3
  4. put value into entryset[index]

Getting a value from the map

  1. calculate hashcode for key
  2. compute index from hashcode (more or less index = hashcode value % size of keyset)
  3. if keyset[index] is not null
    1. if keyset[index] != key (ie. for strings, use strcmp) increment index modulus size of keyset, then goto 3
  4. if keyset[index] is null return null
  5. return entryset[index]

Deleting an entry from the map

  1. calculate hashcode for key
  2. compute index from hashcode (more or less index = hashcode value % size of keyset)
  3. if keyset[index] is not null
    1. if keyset[index] != key (ie. for strings, use strcmp) increment index modulus size of keyset, then goto 3
  4. set keyset[index] and entryset[index] to null

As you can see, you can put step 1 to 3 into a function int findIndexFromKey(Map *map, char *key); and most of the work is done

** EDIT **

Of course, you also have to check if your map is not full before (or while) adding a new entry, otherwise you'll just loop undefinitely.

🌐
Github
cdacamar.github.io › data structures › algorithms › benchmarking › mapping-strings
Mapping Strings in C++ - invoke::thought()
April 9, 2017 - We use strings in order to obtain a handle to some internal type. Don’t worry we’ll get to benchmarks and how we can make this particular implementation faster. Good question. Let’s use one: // using same 'types_t' std::map<std::string, types_t> m; m["circle"] = types_t::circle; m["square"] = types_t::square; m["triangle"] = types_t::triangle;
Top answer
1 of 2
5
map<char*,int> mapp;

They key type here is not "c string". At least not, if we define c string to be "an array of characters, with null terminator". The key type, which is char*, is a pointer to a character object. The distinction is important. You aren't storing strings in the map. You are storing pointers, and the strings live elsewhere.

Unless you use a custom comparison function object, std::map uses operator<(const key_type&,key_type&) by default. Two pointers are equal if, and only if they point to the same object.

Here is an example of three objects:

char A[] = "apple";
char B[] = "apple";
const char (&C)[6] = "apple"

First two are arrays, the third is an lvalue reference that is bound to a string literal object that is also an array. Being separate objects, their address is of course also different. So, if you were to write:

mapp[A] = 10;
std::cout << mapp[B];
std::cout << mapp[C];

The output would be 0 for each, because you hadn't initialized mapp[B] nor mapp[C], so they will be value initialized by operator[]. The key values are different, even though each array contains the same characters.

Solution: Don't use operator< to compare pointers to c strings. Use std::strcmp instead. With std::map, this means using a custom comparison object. However, you aren't done with caveats yet. You must still make sure that the strings must stay in memory as long as they are pointed to by the keys in the map. For example, this would be a mistake:

char A[] = "apple";
mapp[A] = 10;
return mapp; // oops, we returned mapp outside of the scope
             // but it contains a pointer to the string that
             // is no longer valid outside of this scope

Solution: Take care of scope, or just use std::string.

2 of 2
0

It can be done but you need a smarter version of string:

struct CString {
    CString(const char *str) {
        strcpy(string, str);
    }
    CString(const CString &copy); // Copy constructor will be needed.
    char string[50]; // Or char * if you want to go that way, but you will need
                     // to be careful about memory so you can already see hardships ahead.
    bool operator<(const CString &rhs) {
        return strcmp(string, rhs.string) < 0;
    }
}

map<CString,int> mapp;
mapp["someString"] = 5;

But as you can likely see, this is a huge hassle. There are probably some things that i have missed or overlooked as well.

You could also use a comparison function:

struct cmpStr{
    bool operator()(const char *a, const char *b) const {
        return strcmp(a, b) < 0;
    }
};

map<char *,int> mapp;
char A[5] = "A";
mapp[A] = 5;

But there is a lot of external memory management, what happens if As memory goes but the map remains, UB. This is still a nightmare.

Just use a std::string.

🌐
CERN
root-forum.cern.ch › t › map-string-string-in-cint › 9598
Map<string, string> in CINT - ROOT - ROOT Forum
February 3, 2010 - Hi all, I was wondering what is the official way to have CINT understand map ; I’ve tried using #pragma link C++ class std::map ; but this doesn’t seem to work. Here’s my short test script: #if !defined(__CINT__) || defined(__MAKECINT__) #include #include //#include //#include int main() #endif #if defined(__CINT__) #pragma link C++ class std::map ; void testCINT() #endif { std::cout
🌐
Medium
medium.com › @staytechrich › cpp-025-understanding-std-map-and-functional-mapping-in-c-a023134e9895
cpp_025: Understanding std::map and Functional Mapping in C++ | by CodeAddict | Medium
April 27, 2025 - std::map is an STL container that stores key-value pairs in a sorted order (by keys). Each key is unique, and the map provides fast lookup, insertion, and deletion operations. ... Keys: Integers like 1, -1, 10.
🌐
Cplusplus
cplusplus.com › reference › map › map
std::map
The elements in the container follow a strict order at all times. All inserted elements are given a position in this order. ... Each element associates a key to a mapped value: Keys are meant to identify the elements whose main content is the mapped value.
🌐
Tech Couch
tech-couch.com › post › the-complete-guide-to-c-strings
The complete guide to C strings - Tech Couch
June 13, 2026 - The C language has no builtin string type, only char with a size of 1 byte. The ASCII standard maps each of its 128 possible values to an english or control character. (A byte has 8 bits, but one was reserved historically, leaving only 2^7 = ...