- Pascal 教程
- Pascal - 首頁
- Pascal - 概述
- Pascal - 環境搭建
- Pascal - 程式結構
- Pascal - 基本語法
- Pascal - 資料型別
- Pascal - 變數型別
- Pascal - 常量
- Pascal - 運算子
- Pascal - 決策
- Pascal - 迴圈
- Pascal - 函式
- Pascal - 過程
- Pascal - 變數作用域
- Pascal - 字串
- Pascal - 布林值
- Pascal - 陣列
- Pascal - 指標
- Pascal - 記錄
- Pascal - 變體
- Pascal - 集合
- Pascal - 檔案處理
- Pascal - 記憶體
- Pascal - 單元
- Pascal - 日期和時間
- Pascal - 物件
- Pascal - 類
- Pascal 有用資源
- Pascal - 快速指南
- Pascal - 有用資源
- Pascal - 討論
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 支援的所有集合運算子。假設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 (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]
廣告