建立一个字典 - 字典树/指针

可以在程序内修改词条,也可以在 dictionary.txt 内修改。

  • 词语/短语/句子
  • 释义
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<fstream>
#include<windows.h>
#include<vector>
using namespace std;
class item{
	string str;
	public:
		item(string ori):str(ori){}
		void print(){cout<<str<<endl;}
};
struct tnode{
	tnode *nxt[52];
	item *it;
	tnode():nxt{0},it(NULL){}
};
tnode *root=NULL;
bool Tinsert(string s,string m){
	int len=s.size();
	tnode *p=root;
	for(int i=0;i<len;i++)
		if(!islower(s[i])&&!isupper(s[i])){
			puts("Illegal Input");
			return false;
		}
	for(int i=0;i<len;i++){
		int tar=islower(s[i])?s[i]-'a':s[i]-'A'+26;
		if(p->nxt[tar]==NULL)
			p->nxt[tar]=new tnode;
		p=p->nxt[tar];
	}
	if(p->it==NULL){puts("Successfully insert.");p->it=new item(m);return true;}
	puts("Fail to insert.");return false;
}

void Tsearch(string s){
	int len=s.size();
	tnode *p=root;
	for(int i=0;i<len;i++)
		if(!islower(s[i])&&!isupper(s[i])){
			puts("Illegal Input");
			return ;
		}
	for(int i=0;i<len;i++){
		p=p->nxt[islower(s[i])?s[i]-'a':s[i]-'A'+26];
		if(p==NULL){puts("There's no such word in the dictionary.");return;}
	}
	if(p->it==NULL){puts("There's no such word in the dictionary.");return;}
	p->it->print();
}
HWND asdf;
signed main(){
	root=new tnode;
	ofstream fout;fout.open("dictionary.txt",ios_base::app);
	ifstream fin;fin.open("dictionary.txt",ios_base::in);
	string s,m;bool flag=true;
	int cnt=0;vector<int>wrong_item;
	while(fin>>s>>m){
		cnt++;
		if(!Tinsert(s,m)){
			flag=false;
			wrong_item.push_back(cnt);
		}
	}
	Sleep(200);
	puts("Initialize complete.");
	if(!flag){
		puts("WARNING! There're illegal items in the dictionary!");
		for(int i=0,l=wrong_item.size();i<l;i++)
			printf("On row %d\n",wrong_item[i]);
	}
	system("pause");
	system("cls");
	while(1){
		string word,meaning;
		int opt=MessageBox(asdf,"Search (Yes) Insert (No)","Option",MB_YESNOCANCEL);
		if(opt==7){
			getline(cin,word);
			getline(cin,meaning);
			if(Tinsert(word,meaning))fout<<word<<' '<<meaning<<endl;
		}
		else if(opt==6)getline(cin,word),Tsearch(word);
		else break;
	}
	return 0;
}
posted @   robinyqc  阅读(28)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示