C++;映射以使用字符串值作为键 我想使用C++标准映射从一个字符串键映射到另一个对象(例如,整数),但是它看起来好像C++使用指针作为键,而不是 char *: #包括 #包括 #包括 使用名称空间std; int main() { std::map m; const char*j=“键”; m、 插入(std::make_pair((char*)j,5)); char*l=(char*)malloc(strlen(j)); strcpy(l,j); printf(“%s\n”、“key”); printf(“%s\n”,j); printf(“%s\n”,l); //检查是否在地图中键入->如果是0,如果不是1 printf(“%d\n”,m.find((char*)“key”)==m.end(); printf(“%d\n”,m.find((char*)j)=m.end(); printf(“%d\n”,m.find((char*)l)=m.end(); }

C++;映射以使用字符串值作为键 我想使用C++标准映射从一个字符串键映射到另一个对象(例如,整数),但是它看起来好像C++使用指针作为键,而不是 char *: #包括 #包括 #包括 使用名称空间std; int main() { std::map m; const char*j=“键”; m、 插入(std::make_pair((char*)j,5)); char*l=(char*)malloc(strlen(j)); strcpy(l,j); printf(“%s\n”、“key”); printf(“%s\n”,j); printf(“%s\n”,l); //检查是否在地图中键入->如果是0,如果不是1 printf(“%d\n”,m.find((char*)“key”)==m.end(); printf(“%d\n”,m.find((char*)j)=m.end(); printf(“%d\n”,m.find((char*)l)=m.end(); },c++,dictionary,C++,Dictionary,输出: key key key 0 0 1 有没有办法让地图的关键是“值”/键的内容,类似于C++中的其他语言,比如JavaScript?< P>,你真的想用 STD::String < /代码>来表示字符串,而不是用老的/C风格 char *方式来做字符串。以下是使用std::string完成程序时的外观: #include <iostream> #include <map> #include <string> using namespace std;

输出:

key
key
key
0
0
1

有没有办法让地图的关键是“值”/键的内容,类似于C++中的其他语言,比如JavaScript?

< P>,你真的想用<代码> STD::String < /代码>来表示字符串,而不是用老的/C风格<代码> char *<代码>方式来做字符串。以下是使用
std::string
完成程序时的外观:

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
{
    std::map<string, int> m;

    const char *j = "key";
    m.insert(std::make_pair(j, 5));

    std::string l = j;

    printf("%s\n", "key");
    printf("%s\n", j);
    printf("%s\n", l.c_str());

    // Check if key in map -> 0 if it is, 1 if it's not
    printf("%d\n", m.find("key") == m.end());
    printf("%d\n", m.find(j) == m.end());
    printf("%d\n", m.find(l) == m.end());
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
std::map m;
const char*j=“键”;
m、 插入(标准::制作成对(j,5));
std::字符串l=j;
printf(“%s\n”、“key”);
printf(“%s\n”,j);
printf(“%s\n”,l.c_str());
//检查是否在地图中键入->如果是0,如果不是1
printf(“%d\n”,m.find(“key”)==m.end();
printf(“%d\n”,m.find(j)=m.end());
printf(“%d\n”,m.find(l)=m.end());
}

std::map m??使用
std::string
作为键,或声明自定义字符串比较谓词并将其包含在映射模板中。请注意,如果执行后一种操作,则必须绝对确保正确管理字符串指针。我应该指出,你所有的常量转换都是为了避开非常量
char*
键值,这强烈表明你的设计有缺陷,你正在使用黑客来规避有效的编译错误。你为什么要这样做?!R U了解
std::string
?看看FWIW,下面是您的示例,它被修改为使用C字符串的自定义比较器:--除非您确实知道自己需要它,否则这几乎肯定是可以避免的(也就是说,您已经远远超过了初学者甚至中级程序员的水平)。选择这种方法的一个有效原因可能是,如果您的程序在缓冲区、数据段或任何地方包含大量字符串资源,并且您希望在运行时构建映射而不复制字符串。为什么您使用
printf
而不是
std::cout
std::format
?我喜欢
printf()
,我还想演示如何使用
c_str()
std::string
和需要
const char*
的函数之间进行接口。此外,我不想改变提问者的程序,而不是为了证明我想证明的内容。