2013-04-30 45 views
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; 

} 

预期输出: 所有 所有 所有

在这里输入的代码

实际输出: 所有 所有 呐

+1

你想使用std ::字符串,而不是char const *,因为前者会正确比较两个字符串(即实现一个小于运算符),而后者只是比较指针本身而不是字符串内容。 – 2013-04-30 23:34:56

+0

或者,您可以将自己的二元谓词作为第三个模板参数提供给[std :: map](http://www.cplusplus.com/reference/map/map/),它可以比较您的键。 – 2013-04-30 23:41:27

+0

我同意,但有没有办法做到没有std :: string? C世界是如何做的(我知道地图不在C世界)? – Jazz 2013-04-30 23:44:44

回答

3

std::map使用严格弱排序标准的以表示其内部比较对象,默认为std::less

std::less不会将char*参数视为一个字符串,它只会将它们视为一个指针,它只会检查一个指针是否小于另一个。

但是,你可以(但我猜你应该使用std::string避免混合C和C++),用于比较char*参数,把它们当作字符串创建新类:

#include <cstring> 

struct ConstCharStarComparator 
{ 
    bool operator()(const char *s1, const char *s2) const 
    { 
    return strcmp(s1, s2) < 0; 
    } 
}; 

map<const char*, MarketLang *, ConstCharStarComparator> table;