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";
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP