我正在尝试用2个字符的单词创建一个字典,但没有那么成功这里是我的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
每当我输入单词,然后当我想检查单词是否在字典中时,我总是打印"否"?
我来自Java,所以我习惯了引用,而不是指针,所以我可能错了.我想学习如何正确使用地图,那么请问我在这里应该做些什么?
谢谢
//I heard this is how you check whether a key exists:
bool exists = m.find(chck)==m.end();
Run Code Online (Sandbox Code Playgroud)
是的,但如果元素不存在则条件为真.你应该打电话给你的vaviable notExists:
bool notExists = m.find(chck)==m.end();
Run Code Online (Sandbox Code Playgroud)
现在,如果您要做的就是检查是否存在工作,您可以使用std::set<std::string>.如果你想让这个词成为其他东西的关键,那么你需要std::map<std::string, SomeThingElse>.
忘了那些char*.使用std::strings.
| 归档时间: |
|
| 查看次数: |
27335 次 |
| 最近记录: |