我試圖與2個字符的字的字典,但沒有這麼多的成功 這裏是我的代碼:C++:如何製作一個簡單的字典?
#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;
}
每當我進入的話,然後當我想查一個字是否是在一本字典,我總是打印出「號碼」?
我來自Java所以我習慣了引用,而不是指針,所以這就是我可能錯誤的地方。我想學習如何正確使用地圖,所以你可以請我在這裏應該做什麼?
感謝
有'C++'中的引用,你可以*幾乎*總是使用它們而不是點(我說*幾乎*非常輕微)。不用'*'來指定指針,而是用'&'來引用。 – RageD 2013-03-01 21:39:03
問題就像你想的 - 指針與引用。你的地圖存儲指向字符的指針作爲關鍵字,因爲它們都在堆棧中,所以它們永遠不會相同。你可以使用字符串而不是char *嗎? – 2013-03-01 21:42:41
對於它的價值,Java變量(對於引用類型)的FAR更像C++指針,而不像C++引用。 – 2016-10-11 18:39:52