อาร์เรย์คู่ขนานคือโครงสร้างที่มีหลายอาร์เรย์ แต่ละอาร์เรย์เหล่านี้มีขนาดเท่ากันและองค์ประกอบอาร์เรย์มีความสัมพันธ์กัน องค์ประกอบทั้งหมดในอาร์เรย์คู่ขนานเป็นตัวแทนของเอนทิตีทั่วไป
ตัวอย่างของ Parallel Array มีดังนี้ −
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
ในโปรแกรมด้านบนนี้ มีการประกาศอาร์เรย์สามชุดซึ่งประกอบด้วยชื่อพนักงาน แผนก และเงินเดือนตามลำดับ ด้านล่างนี้ −
string empName [ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" };
string empDept [ ] = {"IT", "Sales", "IT", "HR", "Sales"};
int empSal[ ] = {10000, 5000, 20000, 12000, 5000 }; เงินเดือนสูงสุดพบได้โดยใช้ for loop และเก็บไว้ใน max. ดัชนีที่มีเงินเดือนสูงสุดจะถูกเก็บไว้ในดัชนี ด้านล่างนี้ −
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";