关键技术:vector容器
代码:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef struct __Record{
string key;
string value;
}Record;
class Dic{
public:
bool insert(string,string);
bool del(string);
bool has_key(string);
string get(string);
int size();
void clear();
private:
vector<Record> vec_0;
};
bool Dic::insert(string key,string value){
Record rec;
if(has_key(key)){
cout<<"Error!Duplicate key!Insert failed!"<<endl;
return false;
}
rec.key = key;
rec.value = value;
vec_0.push_back(rec);
return true;
}
bool Dic::del(string key){
if(!has_key(key)){
cout<<"Error!No such key!Delete failed!"<<endl;
return false;
}
for(vector<Record>::iterator it = vec_0.begin(); it != vec_0.end();){
if(!it->key.compare(key)){
it = vec_0.erase(it);
}else{
it++;
}
}
}
bool Dic::has_key(string key){
bool res = false;
for(vector<Record>::iterator it = vec_0.begin(); it != vec_0.end();it++){
if(!it->key.compare(key)){
res = true;
}
}
return res;
}
string Dic::get(string key){
string res;
for(vector<Record>::iterator it = vec_0.begin(); it != vec_0.end();it++){
if(!it->key.compare(key)){
res = it->value;
}
}
return res;
}
int Dic::size(){
return vec_0.size();
}
void Dic::clear(){
vec_0.clear();
}
int main(){
Dic dic_0;
dic_0.insert("a","used before a noun to refer to a single thing or person that has not been mentioned before, especially when you are not referring to a particular thing or person");
dic_0.insert("b","John Winston Lennon (b. 9 October 1940, Liverpool, d. 8 December 1980, New York)");
dic_0.insert("c","an object-oriented version of C (= a computer programming language)");
dic_0.insert("c","aeee33a");
cout<<"a:"<<dic_0.get("a")<<endl;
cout<<"c:"<<dic_0.get("c")<<endl;
cout<<"b:"<<dic_0.get("b")<<endl;
cout<<dic_0.get("b111")<<endl;
dic_0.del("q");
cout<<"the dictionary size is "<<dic_0.size()<<endl;
dic_0.clear();
cout<<"the dictionary size is "<<dic_0.size()<<endl;
return 0;
}
运行测试:
