delphi 集合的用法
(2012-10-03 07:50:20)delphi基础补充
我觉得,集合很实用,以前在程序中总要先从数据库中取出好多元素,然后逐个判断,现在知道集合这个概念,兴奋ing!哈哈啊。
集合是P a s c a l特有的数据类型,在Visual Basic、C或C + +都没有(虽然C++ Builder提供了一种模
板类称为集合,它模仿P a s c a l集合的行为)。集合用一种有效的手段来表示一组有序数、字符和枚
举值。
声明一个集合用关键字set of,并在其后跟上有序类型或一个集合可能值的有限子集。示例如下:
type
TCharSet=set of char; // 可能的值:# 0 - # 2 5 5
TEnum = ( Monday, Tuesday, Wednesday, Thursday, Friday ) ;
TEnumSet=set of TEnum; // 包含了T E n u m值的任何组合
TSubrangeSet=set of 1..10; // 可能的值:1 - 1 0
TAlphaSet=Set of 'A'..'z';
注意,一个集合最多只能有2 5 5个元素。另外,只有有序的类型才能跟关键字 set of,因此下列的
代码是非法的:
t y p e
TIntSet=set of Integer; // 非法:太多的元素
TStrSet=set of string;
集合在内部以位的形式存储它的元素,这使得在速度和内存利用上更有效。集合如果少于 3 2个元
素,它就存储在C P U的寄存器中,这样效率就更高了,为了用集合类型得到更高的效率。记住,集合
的基本类型的元素数目要小于3 2。
1. 使用集合
当使用集合的元素时,使用方括号。下面代码表明如何使用集合类型的变量并给它赋值。
(1)直接在所在过程中var中定义:
var
SubrangeSet:set of 1..10;(可能是1到10中任何数)
begin
SubrangeSet:=[1,2,4..6];
end;
(2)在Type中定义:
type
TCharSet=set of char;
var
CharSet:TCharSet;
begin
CharSet:=['A'..'J','a','m'];
end;
2. 集合操作符
Object Pascal提供了几个用于集合的运算符,用这些运算符可以判断集合和集合之间的关系,对
合增删元素,对集合进行求交集运算。
(1) 关系运算
用in运算符来判断一个给定的元素是否在一个集合中,下面的代码判断在前面所定义的集合
CharSet中是否有字母‘S’:
if 'S' in CharSet then
/ /继续运行
下面的代码判断在EnumSet中是否没有Monday :
if not (Monday in EnumSet) then
/ /继续运行
(2) 增删元素
用+、-运算符或Include( )和Exclude( )过程,能对一个集合变量增删元素:
Include(CharSet, 'a');/ /在集合中增加'a' ;
CharSet : = CharSet+['b'] ;/ /在集合中增加'b' ;
Exclude(CharSet, 'x');/ /在集合中删除'x' ;
CharSet:=CharSet-['y', 'z'];/ /在集合中删除'y'和'z' ;
提示 尽可能地用Include()和Exclude()来增删元素,尽可能地少用+、-运算符。因为Include()和
Exclude()仅需要一条机器指令,而+和-需要13+6n(n是集合的按位的长度)条机器指令。
(3) 交集
用*运算符来计算两个集合的交集,表达式Set1 * Set2的结果是产生的集合的元素在Set1和
Set2集合
都存在,下面的例子用来判断在一个给定的集合中是否有某几个元素:
if {'a', 'b', 'c'}*CharSet={'a', 'b', 'c'} then
/ /继续程序
另一篇文章//
interface
uses
Forms,
type
var
implementation
{$R *.dfm}
procedure TForm4.Button1Click(Sender: TObject);
var
begin
end;
procedure TForm4.Button2Click(Sender: TObject);
var
begin
end;
//初始化
procedure TForm4.Button3Click(Sender: TObject);
begin
end;
//集合减少
procedure TForm4.Button5Click(Sender: TObject);
begin
end;
//集合增加
procedure TForm4.Button6Click(Sender: TObject);
begin
end;
//集合减少
procedure TForm4.Button7Click(Sender: TObject);
begin
end;
//集合增加
procedure TForm4.Button4Click(Sender: TObject);
begin
end;
//执行校验
procedure TForm4.Button8Click(Sender: TObject);
begin
end;
//取得集合的交集
procedure TForm4.Button9Click(Sender: TObject);
begin
end;
end.
———————————————————————————————————————
—————————————————————
———————————————————————————————————————
—————————————————————
object Form4: TForm4
///另一篇文章///
DELPHI集合类型
点击:
,如,整型、布尔型、字符型、枚举型和子界型。
其中,基类型是指集合中的元素必须是同一有序数据类型。Pascal语言规定集合的元素个
数最多不得超过256个;因此基类型的序数值必须在O~255之间,例如:
重复出现o
还有
“=”、“<>"表示集合相等和集合不等,例如:[1,2]<=[1..3]的结果是true;1 in
[O..6]的结果是true。
end