并行数组是包含多个数组的结构。这些数组中的每个数组都具有相同的大小,并且数组元素彼此相关。并行数组中的所有元素都代表一个公共实体。
并行数组的示例如下-
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。中。包含最高薪水的索引存储在索引中。这如下所示-
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";