|
这是一个map对象保存的程序,我弄不清楚的是书上说定义word类对象的运算符<,是为了维护一个有序的关健字列表,那这个运算符是什么时候调用的呢?又是怎么完成关健字有序的呢?还有关于 word (){strcpy(str,"");} 和 word(char *s){strcpy(str,s);}在程序中又起到什么作用呢?无参的构造函数有被调用过吗?它们是在dictionary.insert(pair<word,meaning>(word("house"),meaning("a place of dwelling.")));等一系列语句的实现中被调用的吗?可这个插入语句并没有创建对象啊,那它又是怎样实现一个有序的序列的呢?这些疑惑真是把我给弄的晕了!还请大家多多指教!!!谢谢
#include <iostream>
#include <map>
#include <cstring>
using namespace std;
class word{
char str[20];
public:
word (){strcpy(str,"");}
word(char *s){strcpy(str,s);}
char *get(){return str;}
};
bool operator<(word a,word b){
return strcmp(a.get(),b.get())<0;
}
class meaning{
char str[80];
public:
meaning(){strcmp(str,"");}
meaning(char *s){strcpy(str,s);}
char *get(){return str;}
};
int main()
{
map<word,meaning>dictionary;
dictionary.insert(pair<word,meaning>(word("house"),meaning("a place of dwelling.")));
dictionary.insert(pair<word,meaning>(word("keyboard"),meaning("an input device.")));
dictionary.insert(pair<word,meaning>(word("programming"),meaning("the act of writing a program.")));
dictionary.insert(pair<word,meaning>(word("stl"),meaning("standard template library")));
char str[80];
cout<<"enter word";
cin>>str;
map<word,meaning>::iterator p;
p=dictionary.find(word(str));
if(p!=dictionary.end())
cout<<"definition"<<p->second.get();
else
cout<<"word not in dictionary.\n";
return 0;
} |
|