Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;:如何制作一本简单的词典?_C++_Dictionary - Fatal编程技术网

C++ C++;:如何制作一本简单的词典?

C++ C++;:如何制作一本简单的词典?,c++,dictionary,C++,Dictionary,我正试着编一本有两个字符的单词的字典,但没有成功 这是我的密码: #include <cstdlib> #include <iostream> #include <map> using namespace std; int main(int argc, char *argv[]){ map<char*,int> m; //input 5 two-lengthed words for (int i=0;i<5;i++

我正试着编一本有两个字符的单词的字典,但没有成功 这是我的密码:

#include <cstdlib>
#include <iostream>
#include <map>
using namespace std;

int main(int argc, char *argv[]){
    map<char*,int> m;
    //input 5 two-lengthed words 
    for (int i=0;i<5;i++){
        char s[3];
        cin>>s;
        s[2] = '\0';
        m[s]=1; //add a key
    }
    //checking if a word exists.

    cout<<"Word you want to check whether it exists:"<<endl;
    char chck[3];
    cin>>chck;
    chck[2]='\0';
    //I heard this is how you check whether a key exists:
    bool exists = m.find(chck)==m.end(); 
    cout<<((exists)?"Yes!":"No.")<<endl;
    system("pause"); //Yea, system, I know.
    return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(int argc,char*argv[]){
地图m;
//输入5个两个长单词
对于(int i=0;i>s;
s[2]='\0';
m[s]=1;//添加密钥
}
//检查单词是否存在。
库特
是的,但是如果元素不存在,则条件为true。您应该调用VAVALIABLE
notExists

bool notExists = m.find(chck)==m.end();
现在,如果您只想检查工作是否存在,可以使用
std::set
。如果您想让这个词成为其他内容的键,那么您需要
std::map

忘记那些
char*
。使用
std::string
s

    m[s]=1; //add a key
每次“添加一个键”时,实际上只得到相同的元素,使用相同的键。键是数组的地址
s
不是输入的字符串的值

尝试打印出容器的大小,您将看到单个元素:

   std::cout << m.size() << '\n';
要将字符串值推入容器,请使用
std::string
键,而不是
char*

std::string s1 = "foo";
std::string s2 = "foo";
assert( s1 == s2 );   // passes

这避免了比较指针和数组超出范围而在映射中留下悬空指针的整个问题。

让我们稍微看看您的代码:

您有一个
std::map
。第一个“char*”作为映射的键是可疑的。将指针存储为键通常不是您真正想要做的。但我们一直在阅读。在您的循环中,您有一个填充的本地数组s。然后您使用该变量索引到映射中。请记住,映射的键是char*。数组s的地址可能在每个循环迭代。因此,您可能只在映射中放入一个项,而它只保存您放入s的最新值。但请稍候,情况会变得更糟。循环完成后,s将超出范围,现在取消引用当前存储在映射中的指针是未定义的行为(作为该map.Output m.size()中唯一一个元素的键进行验证)


将映射重新定义为
std::map
,以避免所有这些问题。

C++
中有引用,您几乎可以始终使用它们而不是点(我几乎很轻松地说)。与其使用
*
来指定指针,不如查看
&
中的引用。问题就像您的思想-指针与引用一样。您的映射将指向字符的指针存储为键,因为它们都在堆栈上,所以它们永远不会相同。您可以使用字符串而不是字符*?值得一提的是,Java variabLES(参考类型)远比C++指针更像C++指针,或者只是<代码> BoOL存在= M.Debug(CHCK)!= m();<代码> HMM,Yes,你在那里。但是,我仍然得到“是的”!当它存在或不存在时,两者都使用。@SmRndGuy这可能是代码中的其他错误。例如,请参阅。这是因为您仍然使用
char*
作为键,而不是
std::string
您可以使用`字符标记代码,反引号中的文本不会被视为HTML,因此您可以使用
ins代替和
 char s1[] = "foo";
 char s2[] = "foo";
 assert( s1 == s2 );   // FAILS!
std::string s1 = "foo";
std::string s2 = "foo";
assert( s1 == s2 );   // passes