const char *在地图中找不到 [英] const char* not found in map find
问题描述
我有一个小程序,我试图在地图中搜索一个特定的字符串,我得到正确的结果,如果我传递静态const字符串us找到,但它不工作,如果我复制一个字符串到指针。
我不知怎么想,它试图比较传递的字符串的地址。我计划摆脱std :: string从由于某些原因。
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;
}
预期输出:
all
all
all
Expected output: all all all
在此输入代码
实际输出:
all $ b b all
na
Actual output: all all na
推荐答案
std :: map
使用由其内部比较对象指示的严格弱排序标准,其默认为 std :: less
。
std::map
is using strict weak ordering criterion indicated by its internal comparison object, which is defaulted to the std::less
.
std :: less
不会处理 char *
参数作为一个字符串,它只会看到它们作为指针,它只是检查一个指针是否小于另一个。
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.
但是,你可以猜猜你应该使用 std :: string
避免混合C和C ++),创建一个新类来比较 char *
,将它们视为字符串:
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;
这篇关于const char *在地图中找不到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!