今天学习了C#中的三种数据结构:字典(Dictionary)、栈(Stack)、队列(Queue)
1.字典 (Dictionary):
字典相当于C++中的map,是能保存键值对的集合。
使用字典之前需要调用 System.Collections.Generic
using System;
using System.Collections.Generic;
namespace Lesson23_2
{
//字典 Dictionary
//字典中的 key 都是唯一的,不允许重复
//引入泛型集合命名空间 System.Collections.Generic
class MainClass
{
public static void Main (string[] args)
{
//创建一个字典对象,Key的类型是 string
//字典是用来保存键值对的集合
//name <key , value>
Dictionary<string , int> dic = new Dictionary<string, int> ();
//1.Add() 用来添加键值对
dic.Add ("dzzhyk",18);
//2.通过 Key 获取 Value
Console.WriteLine (dic["dzzhyk"]);
//3.Remove() 从字典中移除键值对
dic.Remove ("dzzhyk");
//4.获取当前字典中 value 的个数
int count = dic.Count;
Console.WriteLine (count);
//5.检查字典中是否包含指定的 key 或者 Value
bool a = dic.ContainsKey ("dzzhyk");
bool b = dic.ContainsValue (13);
//6.尝试获取指定的 key 所对应的 value
int s;
//如果当前字典中包含 dzzhyk 这个 key 就获取对应的 value ,并且保存在S中,
//整个方法的反回值是true ; 如果不存在这个 Key ,就返回false
bool bb = dic.TryGetValue ("dzzhyk", s);
}
}
}
有关字典的操作比较好理解,其中:TryGetValue()比较有意思,这个函数本身返回一个布尔类型的数值,他的作用是在当前的这个字典集合中查找为键值Key的元素,如果存在,就把这个键值所对应的数值输出给另一个变量,自身返回true;否则,就返回false。
2.栈 (Stack)、队列 (Queue):
对于栈和队列的定义相对来说比较熟悉,因此直接贴上代码:
在使用栈和队列之前,需要先调用 System.Collections.Generic
using System;
using System.Collections.Generic;
namespace Lesson24_2
{
//栈和队列
//使用命名空间 System.Collections.Generic
class MainClass
{
public static void Main (string[] args)
{
//栈
Stack <string> s = new Stack<string> ();
//1.入栈
s.Push ("dzzhyk");
s.Push ("hello");
s.Push ("yes");
//2.出栈 - 不能指定元素
//pop出栈顶的元素
string s1 = s.Pop ();
Console.WriteLine (s1);
s1 = s.Pop ();
Console.WriteLine (s1);
s1 = s.Pop ();
Console.WriteLine (s1);
//其他有关栈的操作基本相似
int count = s.Count;
s.Clear ();
bool b = s.Contains ("dzzhyk");
//队列
Queue<string> q = new Queue<string> ();
//1.向队列中添加元素
q.Enqueue ("dzzhyk");
q.Enqueue ("hello");
q.Enqueue ("yes");
//2.获取队列中的元素 , 先入队的先出
string s2 = q.Dequeue ();
Console.WriteLine (s2);
s2 = q.Dequeue ();
Console.WriteLine (s2);
s2 = q.Dequeue ();
Console.WriteLine (s2);
//3.其他的操作基本类似
}
}
}
在使用栈和队列的时候,要注意入栈、出栈;入队、出队的操作和一般数据结构的操作不同:
栈:入栈:push ( );
出栈:pop ( );
队列:入队:Enqueue ( ); 出队:Dequeue ( );