问题
I have a small program, I am trying to search for a particular string in the map, I get correct result if I pass static const string "us" to find but it doesn't work if I copy a string to pointer. I somehow think that it is trying to compare the address of the string that is passed. I am planning to get rid of std::string from due to some reason.
using namespace std;
static struct MarketLang {
const char* market;
const char* lang;
} market_lang[] = {
{"us", "all"},
{"el", "en,fr,it,de,es"},
{"xx", "na"},
};
class MarketLangMap {
map<const char*, MarketLang *> table;
public:
MarketLangMap() {
int TOTAL_MARKET_INFO = sizeof(market_lang)/sizeof(MarketLang);
for (int i = 0; i < TOTAL_MARKET_INFO; i++) {
table[market_lang[i].market] = market_lang+ i;
}
}
MarketLang *operator[](const char* s) {
if (table.find(s) != table.end()) {
return table.find(s)->second;
} else {
return table.find("xx")->second;
}
}
};
int
main()
{
MarketLangMap *m = new MarketLangMap();
const char* r = "us";
char* p = new char(10);
strcpy(p, "us");
std::cout<<(*m)["us"]->lang <<std::endl;``
std::cout<<(*m)[r]->lang <<std::endl;
std::cout<<(*m)[p]->lang <<std::endl;
}
Expected output: all all all
enter code here
Actual output: all all na
回答1:
std::map
is using strict weak ordering criterion indicated by its internal comparison object, which is defaulted to the std::less
.
std::less
will not treat char*
arguments as a string, it will just see them as a pointers, and it will just check if one pointer is less than the other.
However, you can (but I guess you should use std::string
to avoid mixing C and C++), create new class for comparing char*
arguments, treating them as strings:
#include <cstring>
struct ConstCharStarComparator
{
bool operator()(const char *s1, const char *s2) const
{
return strcmp(s1, s2) < 0;
}
};
map<const char*, MarketLang *, ConstCharStarComparator> table;
来源:https://stackoverflow.com/questions/16310565/const-char-not-found-in-map-find