1
我有一个小程序,我试图在地图中搜索特定的字符串,如果我传递静态常量字符串“我们”来查找它但没有找到正确的结果如果我将一个字符串复制到指针上工作。 我以某种方式认为它试图比较传递的字符串的地址。我打算从某些原因中删除std :: string。const char *在地图中找不到
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;
}
预期输出: 所有 所有 所有
在这里输入的代码
实际输出: 所有 所有 呐
你想使用std ::字符串,而不是char const *,因为前者会正确比较两个字符串(即实现一个小于运算符),而后者只是比较指针本身而不是字符串内容。 – 2013-04-30 23:34:56
或者,您可以将自己的二元谓词作为第三个模板参数提供给[std :: map](http://www.cplusplus.com/reference/map/map/),它可以比较您的键。 – 2013-04-30 23:41:27
我同意,但有没有办法做到没有std :: string? C世界是如何做的(我知道地图不在C世界)? – Jazz 2013-04-30 23:44:44