❶ 急急急!!!!用c语言实现字典 要求:用无序双向循环链表实现字典的基本操作如下
#include <stdafx.h> //这行是VC编译时要的头文件,你若TC就不要本行了
#include <stdio.h>
typedef struct dictnode{char *key; char *value; dictnode *pre; dictnode *next;} DictNode;
DictNode *pHead = NULL;
//(1)make:构造空的字典
int make()
{
if(pHead)return -1;
pHead = (DictNode*)malloc(sizeof(DictNode));
memset(pHead,0,sizeof(DictNode));
pHead->pre = pHead;
pHead->next = pHead;
return 0;
}
//(2)size:返回字的字典中记录数
int size()
{
int i;
DictNode*p;
for(i=0,p=pHead; p->next!=pHead; p=p->next,i++);
return i;
}
//(3)IsEmpy:如果字典为空则返回真,否则返回假
int IsEmpy()
{
return (pHead->pre==pHead);
}
//(4)Clear:将字典重置为空
void Clear()
{
DictNode* p,*ptmp;
for(p=pHead->next; p!=pHead ; )
{
ptmp = p;
p = p->next;
free(ptmp->key);
free(ptmp->value);
free(ptmp);
}
pHead->next = pHead->pre = pHead;//最后一个空节点也是第一个节点
}
//(5)Insert:插入记录到字典
int Insert(char *key,char*value)
{
DictNode* p, *ptmp;
if(!key||!value||!*key||!*value) return -100;//调用错误
ptmp = (DictNode*)malloc(sizeof(DictNode));
if(!ptmp) return -2; //内存不足这种极端的情况很难出现,但有可能
memset(ptmp,0,sizeof(DictNode));
ptmp->key =(char*) malloc(strlen(key)+1);
if(!ptmp->key){free(ptmp);return -2;} //内存不足这种极端的情况很难出现,但有可能
strcpy(ptmp->key,key);
ptmp->value = (char*)malloc(strlen(value)+1);
if(!ptmp->value){free(ptmp->key);free(ptmp); return -2;} //内存不足这种极端的情况很难出现,但有可能
strcpy(ptmp->value,value);
for(p=pHead->next; p->next!=pHead; p=p->next) if(p->key&&!strcmp(p->key,key)) return 1;//记录存在,插入失败
ptmp->next = pHead; pHead->pre = ptmp;
ptmp->pre = p; p->next = ptmp;
return 0;//操作成功返回0
}
//(6)remove:与给定关键字的记录相同则删除,该记录被返回,否则字典保持不变
DictNode* remove(char *key)
{
DictNode* p;
for(p=pHead->next; p!=pHead&&strcmp(p->key,key); p=p->next);
if(p==pHead) return NULL;
p->pre->next = p->next;
p->next->pre = p->pre;
p->pre = p->next = NULL;
return p;//结点p的空间(key value p三个)没有释放,外面要接收返回值并主动释放结点空间或做别的处理如插入另一表中等
}
//(7)IsPrensent:如果存在与给定关键字匹配的记录则返回真,否则返回假
int IsPrensent(char *key)
{
DictNode* p;
for(p=pHead->next; p!=pHead&&strcmp(p->key,key); p=p->next);
return (p!=pHead);
}
//(8)Find:如果存在与给定关键字相同的记录,则返回记录;如果没有找到,则返回空
DictNode* Find(char *key)
{
DictNode* p;
for(p=pHead->next; p!=pHead&&strcmp(p->key,key); p=p->next);
if(p==pHead) return NULL;
return p; //不要对Find返回的记录key值做变更,value值可以修改,value加长时要重新分配空间。因为记录还在字典链表中
}
void main()
{
const char *prtstr = "****************************";
DictNode* ptmp;
char keybuf[80];
char valuebuf[1024];
int c;
make();
while(1)
{
system("cls");//清屏
printf("%s 选择菜单 %s",prtstr,prtstr);
printf("\n\tF---词条查找\n\tI---插入新词条\n\tR---删除词条\n\tC---清空字典\n\tS---显示字典词条数\n\tQ---退出\n");
printf("请选择操作菜单:");
fflush(stdin);
c = getchar();
if(c>='a'&&c<='z') c -= ('a'-'A');//换大写
if(c!='F'&&c!='I'&&c!='R'&&c!='C'&&c!='S'&&c!='Q') continue;
fflush(stdin);
switch(c)
{
case 'F':
printf("词条查找:\n请输入Key值:");scanf("%s",keybuf);
fflush(stdin);
ptmp = Find(keybuf);
if(ptmp){printf("Key:%s Value:%s",ptmp->key,ptmp->value);}
else{printf("没找到词条:%s,你可以先选择插入这个新词条",keybuf);}
break;
case 'I':
printf("插入新词条:\n请输入Key值:");scanf("%s",keybuf);
fflush(stdin);
if(IsPrensent(keybuf)){printf("词条%s已存在\n",keybuf);}
else
{
printf("请输入它的解释:");gets(valuebuf);
if(!Insert(keybuf,valuebuf))printf("插入成功\n");
else printf("插入失败\n");
}
break;
case 'R':
printf("删除词条:\n请输入Key值:");scanf("%s",keybuf);
fflush(stdin);
ptmp = remove(keybuf);
if(ptmp)
{
free(ptmp->value);free(ptmp->key);free(ptmp);
printf("记录key:[%s]已删除\n",keybuf);
}
else
printf("未找到待删除的记录key:[%s]\n",keybuf);
break;
case 'C':
printf("清空字典:\n真的要清吗?\n请输入Yes以确认删除操作(首字母大写):");scanf("%s",keybuf);
fflush(stdin);
if(strcmp(keybuf,"Yes")){printf("放弃了清空操作\n");}
else {Clear();printf("Ok,你坚持操作,现在字典已清空了\n");}
break;
case 'S':
printf("显示字典词条数:\n当前词条总数:%d\n", size());
break;
case 'Q':
Clear(); free(pHead);
printf("Byebye");
exit(0);
}
printf("\n按回车键继续......");
fflush(stdin);
getchar();
}
}
//VC7.1 下调试通过,运行功能正常
❷ c语言各个按键的键值是什么
,用它可以获得键盘上按键的键值,获得键值之后,把它们记住,或者用宏定义,就可以为以后的 判断语句使用,
for example:
#include<stdio.h>
void main(void)
{
int key=0;
clrscr();
while(key != 0x11b) /*0x11b就是ESC键的键值,用它来判断结束,这是我事先知道的,方法是一样的*/
{
key = bioskey(0);
printf("%x ",key);/*把获得的键值用16进制显示*/
}
}
❸ C# Dictionary 用法;
C# Dictionary用法总结
1、用法1:常规用
增加键值对之前需要判断是否存在该键,如果已经存在该键而且不判断,将抛出异常。所以这样每次都要进行判断,很麻烦,在备注里使用了一个扩展方法
publicstaticvoidDicSample1()
{
Dictionary<String,String>pList=newDictionary<String,String>();
try
{
if(pList.ContainsKey("Item1")==false)
{
pList.Add("Item1","ZheJiang");
}
if(pList.ContainsKey("Item2")==false)
{
pList.Add("Item2","ShangHai");
}
else
{
pList["Item2"]="ShangHai";
}
if(pList.ContainsKey("Item3")==false)
{
pList.Add("Item3","BeiJiang");
}
}
catch(System.Exceptione)
{
Console.WriteLine("Error:{0}",e.Message);
}
//判断是否存在相应的key并显示
if(pList.ContainsKey("Item1"))
{
Console.WriteLine("Output:"+pList["Item1"]);
}
//遍历Key
foreach(varkeyinpList.Keys)
{
Console.WriteLine("OutputKey:{0}",key);
}
//遍历Value
foreach(StringvalueinpList.Values)
{
Console.WriteLine("OutputValue:{0}",value);
}
//遍历Key和Value
foreach(vardicinpList)
{
Console.WriteLine("OutputKey:{0},Value:{1}",dic.Key,dic.Value);
}
}
2、用法2:Dictionary的Value为一个数组
///<summary>
///Dictionary的Value为一个数组
///</summary>
publicstaticvoidDicSample2()
{
Dictionary<String,String[]>dic=newDictionary<String,String[]>();
String[]ZheJiang={"Huzhou","HangZhou","TaiZhou"};
String[]ShangHai={"Budong","Buxi"};
dic.Add("ZJ",ZheJiang);
dic.Add("SH",ShangHai);
Console.WriteLine("Output:"+dic["ZJ"][0]);
}
3、用法3: Dictionary的Value为一个类
//Dictionary的Value为一个类
publicstaticvoidDicSample3()
{
Dictionary<String,Student>stuList=newDictionary<String,Student>();
Studentstu=null;
for(inti=0;i<3;i++)
{
stu=newStudent();
stu.Name=i.ToString();
stu.Name="StuName"+i.ToString();
stuList.Add(i.ToString(),stu);
}
foreach(varstudentinstuList)
{
Console.WriteLine("Output:Key{0},Num:{1},Name{2}",student.Key,student.Value.Name,student.Value.Name);
}
}
Student类:
publicclassStudent
{
publicStringNum{get;set;}
publicStringName{get;set;}
}
4 备注:Dictionary的扩展方法使用
///<summary>
///Dictionary的扩展方法使用
///</summary>
publicstaticvoidDicSample4()
{
//1)普通调用
Dictionary<int,String>dict=newDictionary<int,String>();
.TryAdd(dict,1,"ZhangSan");
.TryAdd(dict,2,"WangWu");
.AddOrPeplace(dict,3,"WangWu");
.AddOrPeplace(dict,3,"ZhangWu");
.TryAdd(dict,2,"LiSi");
//2)TryAdd和AddOrReplace这两个方法具有较强自我描述能力,用起来很省心,而且也简单:
dict.AddOrPeplace(20,"Orange");
dict.TryAdd(21,"Banana");
dict.TryAdd(22,"apple");
//3)像Linq或jQuery一样连起来写
dict.TryAdd(10,"Bob")
.TryAdd(11,"Tom")
.AddOrPeplace(12,"Jom");
//4)获取值
StringF="Ba";
dict.TryGetValue(31,outF);
Console.WriteLine("F:{0}",F);
foreach(vardicindict)
{
Console.WriteLine("Output:Key:{0},Value:{1}",dic.Key,dic.Value);
}
//5)下面是使用GetValue获取值
varv1=dict.GetValue(111,null);
varv2=dict.GetValue(10,"abc");
//6)批量添加
vardict1=newDictionary<int,int>();
dict1.AddOrPeplace(3,3);
dict1.AddOrPeplace(5,5);
vardict2=newDictionary<int,int>();
dict2.AddOrPeplace(1,1);
dict2.AddOrPeplace(4,4);
dict2.AddRange(dict1,false);
}
扩展方法所在的类
publicstaticclass
{
///<summary>
///尝试将键和值添加到字典中:如果不存在,才添加;存在,不添加也不抛导常
///</summary>
publicstaticDictionary<TKey,TValue>TryAdd<TKey,TValue>(thisDictionary<TKey,TValue>dict,TKeykey,TValuevalue)
{
if(dict.ContainsKey(key)==false)
dict.Add(key,value);
returndict;
}
///<summary>
///将键和值添加或替换到字典中:如果不存在,则添加;存在,则替换
///</summary>
publicstaticDictionary<TKey,TValue>AddOrPeplace<TKey,TValue>(thisDictionary<TKey,TValue>dict,TKeykey,TValuevalue)
{
dict[key]=value;
returndict;
}
///<summary>
///获取与指定的键相关联的值,如果没有则返回输入的默认值
///</summary>
publicstaticTValueGetValue<TKey,TValue>(thisDictionary<TKey,TValue>dict,TKeykey,TValuedefaultValue)
{
returndict.ContainsKey(key)?dict[key]:defaultValue;
}
///<summary>
///向字典中批量添加键值对
///</summary>
///<paramname="replaceExisted">如果已存在,是否替换</param>
publicstaticDictionary<TKey,TValue>AddRange<TKey,TValue>(thisDictionary<TKey,TValue>dict,IEnumerable<KeyValuePair<TKey,TValue>>values,boolreplaceExisted)
{
foreach(variteminvalues)
{
if(dict.ContainsKey(item.Key)==false||replaceExisted)
dict[item.Key]=item.Value;
}
returndict;
}
}
❹ 为什么C#的Dictionary的Add函数不是把新的键值对添加到字典末尾
各位大侠我也遇到个这么个问题,我把调试过程发下
定义:
是这样的,Dictionary本身不是有序的,这是正常的
❺ 用C语言写个具有查字典功能的程序,谁帮我看看哪里出错了
fgets(a,1000,fp);是读取文件而你的文件打开方式确是
fp=fopen("E:\\13计科外包班\\词典工程\\dict.txt","w");
你是已写的方式打开的
要改成
fp=fopen("E:\\13计科外包班\\词典工程\\dict.txt","r");
望楼主采纳
❻ 列表中嵌入字典访问后如何使个键值横排输出
摘要 字典使用键-值(key-value)存储,具有极快的查找速度。字典和列表不同,字典里的对象是无序的,是通过一对对的键和值来反映一种映射关系。
❼ c# 中Dictionary怎么用
我们用的比较多的非泛型集合类主要有 ArrayList类 和 HashTable类。我们经常用HashTable 来存储将要写入到数据库或者返回的信息,在这之间要不断的进行类型的转化,增加了系统装箱和拆箱的负担,如果我们操纵的数据类型相对确定的化 用 Dictionary<TKey,TValue> 集合类来存储数据就方便多了,例如我们需要在电子商务网站中存储用户的购物车信息( 商品名,对应的商品个数)时,完全可以用 Dictionary<string, int> 来存储购物车信息,而不需要任何的类型转化。
下面是简单的例子,包括声明,填充键值对,移除键值对,遍历键值对
Dictionary<string, string> myDic = new Dictionary<string, string>();
myDic.Add("aaa", "111");
myDic.Add("bbb", "222");
myDic.Add("ccc", "333");
myDic.Add("ddd", "444");
//如果添加已经存在的键,add方法会抛出异常
try
{
myDic.Add("ddd","ddd");
}
catch (ArgumentException ex)
{
Console.WriteLine("此键已经存在:" + ex.Message);
}
//解决add()异常的方法是用ContainsKey()方法来判断键是否存在
if (!myDic.ContainsKey("ddd"))
{
myDic.Add("ddd", "ddd");
}
else
{
Console.WriteLine("此键已经存在:");
}
//而使用索引器来负值时,如果建已经存在,就会修改已有的键的键值,而不会抛出异常
myDic ["ddd"]="ddd";
myDic["eee"] = "555";
//使用索引器来取值时,如果键不存在就会引发异常
try
{
Console.WriteLine("不存在的键""fff""的键值为:" + myDic["fff"]);
}
catch (KeyNotFoundException ex)
{
Console.WriteLine("没有找到键引发异常:" + ex.Message);
}
//解决上面的异常的方法是使用ContarnsKey() 来判断时候存在键,如果经常要取健值得化最好用 TryGetValue方法来获取集合中的对应键值
string value = "";
if (myDic.TryGetValue("fff", out value))
{
Console.WriteLine("不存在的键""fff""的键值为:" + value );
}
else
{
Console.WriteLine("没有找到对应键的键值");
}
//下面用foreach 来遍历键值对
//泛型结构体 用来存储健值对
foreach (KeyValuePair<string, string> kvp in myDic)
{
Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);
}
//获取值得集合
foreach (string s in myDic.Values)
{
Console.WriteLine("value={0}", s);
}
//获取值得另一种方式
Dictionary<string, string>.ValueCollection values = myDic.Values;
foreach (string s in values)
{
Console.WriteLine("value={0}", s);
}
常用的属性和方法如下: 常用属性
属性说明
Comparer
获取用于确定字典中的键是否相等的 IEqualityComparer。
Count
获取包含在 Dictionary中的键/值对的数目。
Item
获取或设置与指定的键相关联的值。
Keys
获取包含 Dictionary中的键的集合。
Values
获取包含 Dictionary中的值的集合。
常用的方法 方法说明
Add
将指定的键和值添加到字典中。
Clear
从 Dictionary中移除所有的键和值。
ContainsKey
确定 Dictionary是否包含指定的键。
ContainsValue
确定 Dictionary是否包含特定值。
Equals
已重载。 确定两个 Object 实例是否相等。 (从 Object 继承。)
GetEnumerator
返回循环访问 Dictionary的枚举数。
GetHashCode
用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object 继承。)
GetObjectData
实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary实例所需的数据。
GetType
获取当前实例的 Type。 (从 Object 继承。)
OnDeserialization
实现 System.Runtime.Serialization.ISerializable接口,并在完成反序列化之后引发反序列化事件。
ReferenceEquals
确定指定的 Object实例是否是相同的实例。 (从 Object 继承。)
Remove
从 Dictionary中移除所指定的键的值。
ToString
返回表示当前 Object的 String。 (从 Object 继承。)
TryGetValue
获取与指定的键相关联的值。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace Test
{
class Program
{
static void Main(string[] args)
{
char[] chars = new char[] { 'a', 'b', 'c', 'a', 'b', 'c', 'c', 'd', 'd', 'e', 'c' };
//存储字符和字符个数
Dictionary<char, int> dic = new Dictionary<char, int>();
foreach (char c in chars)
{
if (dic.ContainsKey(c))
dic[c] += 1;
else
dic.Add(c, 1);
}
//排序
List<KeyValuePair<char, int>> list = new List<KeyValuePair<char, int>>();
foreach (KeyValuePair<char, int> p in dic)
{
int count = list.Count;
for (int i = 0; i < list.Count; i++)
{
if (p.Value > list[i].Value)
{
list.Insert(i, p);
break;
}
else
{
if (p.Value == list[i].Value)
{
if (p.Key < p.Key)
{
list.Insert(i, p);
break;
}
else
continue;
}
else
continue;
}
}
if (count == list.Count)
list.Add(p);
}
//显示字符
string s = "";
foreach (KeyValuePair<char, int> p in list)
{
s += new string(p.Key, p.Value);
}
Console.WriteLine(s);
Console.Read();
}
}
}
摘自csdn 希望能帮助你
❽ 怎么判断字典是否有某个键值 python 3
#dict.values()可以获取所有的键值
d={'1':'a','2':'b','3':'c'}
print(d)
print(d.values())
print('a'ind.values())
print('z'ind.values())
#输出
{'2':'b','1':'a','3':'c'}
dict_values(['b','a','c'])
True
False
❾ C# 如何通过Key键获取Dictionary集合内的Value
很简单,这样的就行:string value=aa["1"];
就可以了,另外告诉你dictionary的时间效率是1,是一个很效率很高的数据结构。
既然时间效率是1,那么我们寻址的时候就是直接寻址,也不需要去遍历dictionary,这就是为什么键必须唯一,不能重复的原因,如果重复了就不可能再是直接寻址的方式了。
❿ c++中怎样读取python字典,获得字典中的key值(一个key中有多个值)和value值
因为这本身就不是字符串啊.你可以约定好,在python脚本中将参数先转换成str,然后C接口这边也接受字符串入参.