อาร์เรย์แบบขนาน (Parallel Array) คือโครงสร้างที่ประกอบด้วยหลายอาร์เรย์ อาร์เรย์แต่ละอันมีขนาดเท่ากัน และองค์ประกอบของอาร์เรย์แต่ละอันเชื่อมโยงกัน ทุกองค์ประกอบในอาร์เรย์แบบขนานแสดงถึงเอนทิตี (entity) เดียวกัน
ตัวอย่างของอาร์เรย์แบบขนาน มีดังนี้:
employee_name = { Harry, Sally, Mark, Frank, Judy }
employee_salary = {10000, 5000, 20000, 12000, 5000}ในตัวอย่างข้างต้น ชื่อและเงินเดือนของพนักงาน 5 คน ถูกเก็บใน 2 อาร์เรย์
โปรแกรมที่สาธิตการใช้งานอาร์เรย์แบบขนาน มีดังนี้:
ตัวอย่าง
#include <iostream>
#include <string>
using namespace std;
int main() {
int max = 0, index = 0;
string empName[ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" };
string empDept[ ] = {"IT", "Sales", "IT", "HR", "Sales"};
int empSal[ ] = {10000, 5000, 20000, 12000, 5000 };
int n = sizeof(empSal)/sizeof(empSal[0]);
for(int i = 0; i < n; i++) {
if (empSal[i] > max) {
max = empSal[i];
index = i;
}
}
cout << "The highest salary is "<< max <<" and is earned by "
<<empName[index]<<" belonging to "<<empDept[index]<<" department";
return 0;
}ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นจะเป็นดังนี้:
The highest salary is 20000 and is earned by Mark belonging to IT department
ในโปรแกรมนี้ ประกาศอาร์เรย์ 3 อาร์เรย์ ซึ่งเก็บชื่อพนักงาน แผนก และเงินเดือนตามลำดับ โค้ดส่วนนี้มีดังนี้:
string empName[ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" };
string empDept[ ] = {"IT", "Sales", "IT", "HR", "Sales"};
int empSal[ ] = {10000, 5000, 20000, 12000, 5000 };หาเงินเดือนสูงสุดโดยใช้ลูป for และเก็บค่าใน max ดัชนีที่มีเงินเดือนสูงสุดถูกเก็บใน index โค้ดส่วนนี้มีดังนี้:
int n = sizeof(empSal)/sizeof(empSal[0]);
for(int i = 0; i < n; i++) {
if (empSal[i] > max) {
max = empSal[i];
index = i;
}
}สุดท้าย แสดงเงินเดือนสูงสุดและชื่อพนักงานพร้อมแผนกที่เกี่ยวข้อง โค้ดส่วนนี้มีดังนี้:
cout << "The highest salary is "<< max <<" and is earned by "<<empName[index]<<" belonging to "<<empDept[index]<<" department";