我有一个小程序,我正在尝试在地图中搜索特定的字符串,如果我传递静态 const 字符串“us”来查找,我会得到正确的结果,但如果我将字符串复制到指针,它就不起作用。我以某种方式认为它正在尝试比较传递的字符串的地址。由于某种原因,我计划摆脱 std::string 。
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;
}
预期输出:全部全部全部
在此处输入代码
实际输出:all all na