POJ2503(有delete函数)

本文介绍了一个基于字典树的应用实例,详细解释了字典树的插入和查询操作,并探讨了C/C++中memcpy函数的正确使用方法,解决因使用不当导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//字典树的一个应用
#include <iostream>
#include<string.h>
#include<stdio.h>
#include<cstdlib>
#include<string>
#include<cstring>
using namespace std;
const int maxnum=26;
struct trie
{
    bool flag;
    trie *next[maxnum];
    char translation[30];
};
trie *root;
void init()
{
    root=(trie *)malloc(sizeof(trie));
    for(int i=0;i<maxnum;i++)
    {
        root->next[i]=NULL;
    }
    root->flag=false;
}
void insert(char *word,char *t)
{
    int i;
    trie *temp=root;
    while(*word!='\0')
    {
        if(temp->next[*word-'a']==NULL)
        {
            trie *cur=(trie *)malloc(sizeof(trie));
            for(i=0;i<maxnum;i++)
                cur->next[i]=NULL;
            temp->next[*word-'a']=cur;
            cur->flag=false;
        }
        temp=temp->next[*word-'a'];
        word++;
    }
    temp->flag=true;
    strcpy(temp->translation,t);
   // memcpy(temp->translation,t,strlen(t));//之前因为这个函数WA了很多发
}
void query(char *word)
{
    int i;
   //cout<<"hah"<<endl;
    trie *temp=root;
    for(i=0;word[i]!='\0';i++)
    {
        if(temp==NULL||temp->next[word[i]-'a']==NULL)
           {
              printf("eh\n");
               return ;
           }
        temp=temp->next[word[i]-'a'];
    }
    //cout<<temp->flag<<"zheng"<<endl;
    if(temp->flag==true)
       {
          printf("%s\n",temp->translation);
       }
    else
         printf("eh\n");
}
void Delete(trie *root)
{
    for(int i = 0; i < 26; i++)
    if(root->next[i] != NULL)
        Delete(root->next[i]);
    delete root;
}
int main()
{
    char s1[30],s[30],s2[30];
    init();
    while(gets(s),s[0])
    {
       int pos=0,k=0;
       while(s[pos++]!=' ')
          s1[pos-1]=s[pos-1];
        s1[pos-1]='\0';
        //cout<<pos<<endl;
       for(int i=pos;s[i]!='\0';i++)
          s2[k++]=s[i];
          s2[k]='\0';
       insert(s2,s1);
    }
    while(scanf("%s",s)!=EOF)
    {
        //cout<<"haha"<<endl;
          query(s);
    }
    Delete(root);
    return 0;
}

//看看字典树就知道了

下面主要来看下memcpy这个函数

c和c++使用的内存拷贝函数,memcpy函数的功能是从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中。

函数原型

void *memcpy(void *dest, const void *src, size_t n);
按道理来说应该是没问题的呀,想不通

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值