If you really want have C strings as keys you need to provide a user defined comparator since otherwise the map will compare the actual pointer values, not the C strings they point at.
Example:
#include <cstring>
#include <iostream>
#include <map>
#include <string>
// a comparator class for C strings
struct cstring_less {
bool operator()(const char* lhs, const char* rhs) const {
return std::strcmp(lhs, rhs) < 0;
}
};
int main() {
// supply the comparator as the third template parameter:
std::map<const char*, bool, cstring_less> test = {
{"Test", false},
{"test2", false}
};
std::string s = "Test";
test[s.c_str()] = true;
for(auto&[k,v] : test) {
std::cout << k << ' ' << v << '\n';
}
}
I really suggest that you use std::string
as Key though.
The current map
can't be used if any of the C strings (that are not string literals) you store pointers to have gone out of scope. The pointers you store are then "dangling" and dereferencing them would make the program have undefined behavior.