C++ 程式實現並行陣列


並行陣列是一種包含多個數組的結構。這些陣列每個都具有相同大小,並且陣列元素彼此相關。並行陣列中的所有元素表示一個一般實體。

以下是並行陣列的一個示例 −

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 迴圈找到最高的工資並將其儲存在 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";

更新於: 25-6-2020

4 千 + 次瀏覽

開始你的 職業

完成課程獲取認證

開始
廣告
© . All rights reserved.