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