Pascal - 集合



集合是相同类型元素的集合。Pascal 允许定义集合数据类型。集合中的元素称为其成员。在数学中,集合是用大括号{}括起来表示的。但是,在 Pascal 中,集合元素用方括号 [] 括起来,称为集合构造器。

定义集合类型和变量

Pascal 集合类型定义如下:

type
set-identifier = set of base type;

集合类型变量定义如下:

var
s1, s2, ...: set-identifier;

或者:

s1, s2...: set of base type;

一些有效的集合类型声明示例如下:

type
Days = (mon, tue, wed, thu, fri, sat, sun);
Letters = set of char;
DaySet = set of days;
Alphabets = set of 'A' .. 'Z';
studentAge = set of 13..20;

集合运算符

您可以对 Pascal 集合执行以下集合运算。

序号 操作与描述
1

并集

这将连接两个集合,并生成一个包含两个集合中成员的新集合。

2

差集

获取两个集合的差集,并生成一个不包含两个集合共有元素的新集合。

3

交集

获取两个集合的交集,并生成一个包含两个集合共有元素的新集合。

4

包含

如果集合 P 中的所有项也都在集合 Q 中,但反过来不是这样,则集合 P 包含在集合 Q 中。

5

对称差

获取两个集合的对称差,并生成一个包含在任一集合中但不包含其交集的元素的集合。

6

包含于

它检查成员资格。

下表显示了 Free Pascal 支持的所有集合运算符。假设S1S2是两个字符集合,使得:

S1 := ['a', 'b', 'c'];

S2 := ['c', 'd', 'e'];

运算符 描述 示例
+ 两个集合的并集

S1 + S2 将生成一个集合

['a', 'b', 'c', 'd', 'e']

- 两个集合的差集

S1 - S2 将生成一个集合

['a', 'b']

* 两个集合的交集

S1 * S2 将生成一个集合

['c']

>< 两个集合的对称差 S1 <> S2 将生成一个集合 ['a', 'b', 'd', 'e']
= 检查两个集合的相等性 S1 = S2 将返回布尔值 False
<> 检查两个集合的不相等性 S1 <> S2 将返回布尔值 True
<= 包含(检查一个集合是否为另一个集合的子集) S1 <= S2 将返回布尔值 False
包含 将元素包含到集合中;基本上是集合和相同基类型的元素的并集

Include (S1, ['d']) 将生成一个集合

['a', 'b', 'c', 'd']

排除 从集合中排除一个元素;基本上是集合和相同基类型的元素的差集

Exclude (S2, ['d']) 将生成一个集合

['c', 'e']

包含于 检查集合中元素的集合成员资格 ['e'] in S2 返回布尔值 True

示例

以下示例演示了其中一些运算符的使用:

program setColors;
type  
color = (red, blue, yellow, green, white, black, orange);  
colors = set of color;  
 
procedure displayColors(c : colors);  
const  
names : array [color] of String[7]  
  = ('red', 'blue', 'yellow', 'green', 'white', 'black', 'orange');  
var  
   cl : color;  
   s : String;  

begin  
   s:= ' ';  
   for cl:=red to orange do  
      if cl in c then  
      begin  
         if (s<>' ') then s :=s +' , ';  
         s:=s+names[cl];  
      end;  
   writeln('[',s,']');  
end;  
 
var  
   c : colors;  
 
begin  
   c:= [red, blue, yellow, green, white, black, orange];
   displayColors(c);

   c:=[red, blue]+[yellow, green]; 
   displayColors(c);  

   c:=[red, blue, yellow, green, white, black, orange] - [green, white];     
   displayColors(c);    

   c:= [red, blue, yellow, green, white, black, orange]*[green, white];     
   displayColors(c);  

   c:= [red, blue, yellow, green]><[yellow, green, white, black]; 
   displayColors(c);  
end.

编译并执行上述代码后,将产生以下结果:

[ red , blue , yellow , green , white , black , orange]
[ red , blue , yellow , green]
[ red , blue , yellow , black , orange]
[ green , white]
[ red , blue , white , black]
广告
© . All rights reserved.