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 集合执行以下集合运算。
| Sr.No | 运算符与说明 |
|---|---|
| 1 |
Union 这会连接两个集合并给出一个包含两个集合中的成员的新集合。 |
| 2 |
Difference 获取两个集合的差异,并给出一个新集合,其中包含两个集合都不常见的元素。 |
| 3 |
Intersection 获取两个集合的交集,并给出一个新集合,其中包含两个集合共有的元素。 |
| 4 |
Inclusion 如果 P 中的所有项目也在 Q 中,则集合 P 包含在集合 Q 中,但反之则不然。 |
| 5 |
Symmetric difference 获取两个集合的对称差并给出一组元素,这些元素位于任一集合中但不在它们的交集中。 |
| 6 |
In 它检查成员资格。 |
下表显示了 Free Pascal 支持的所有集合运算符。 假设S1和S2是两个字符集,这样 −
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 | 包含集合中的一个元素; 基本上它是一个集合和相同基本类型的元素的并集 | Inclusion (S1, ['d']) 将给出一个集合 ['a', 'b', 'c', 'd'] |
| Exclude | 从集合中排除一个元素; 基本上它是集合和相同基本类型的元素的差异 | Exclude (S2, ['d']) 将给出一个集合 ['c', 'e'] |
| In | 检查集合中元素的集合成员身份 | ['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]

