昨天我的一个上财的同学发来一道作业题让我提供思路,也算是帮我复习了一下二维数组包括string变量的操作。
先show一下my code。
#include <iostream>
#include <string>
using namespace std;
void sort(); //定义排序函数
void insert(); //定义插入函数
void del(); //定义删除函数
void show(); //定义打印数组函数
void swap(int); //用于两个数据交换位置
int num_count; //用于统计输入的总人数
string a[2][100]; //全局数组,第一行姓名,第二行薪资
int main()
{
//int count; //用于统计输入的总人数
string staff_name = "";
string b = { 'q' }; //用于判断输入结束
cout << "请分别输入职工的姓名和薪资(空格隔开,输入q表示结束输入):" << endl;
for (int i = 0; i < 100; i++) {
cin >> a[0][i];
if (b == a[0][i]) {
num_count = i; //总共输入了i个人
break;
}
cin >> a[1][i];
}
cout << endl;
//show(a);
//调用排序函数
sort();
//插入新的职工信息
insert();
//删除同名员工的数据
del();
return 0;
}
void sort()
{
if (a == NULL)
cout << "数组为空,无法排序。" << endl;
for (int i = 0; i < num_count - 1; i++) {
for (int m = 0; m < num_count - 1; m++) {
//if (strcmp(a[1][m] , a[1][m + 1])>0)
if (stoi(a[1][m], 0, 10) > stoi(a[1][m + 1], 0, 10)) //将string转换为int比较大小
swap(m);
}
}
cout << "排序后的薪资姓名数据为:" << endl;
show();
return;
//return x[2][100];
}
void insert()
{
cout << "请输入要插入的姓名和薪资(以空格分割):";
cin >> a[0][num_count] >> a[1][num_count];
num_count++;
sort();
return;
}
void del()
{
string name;
if (a == NULL)
cout << "数组为空,无法删除。" << endl;
cout << "请输入要删除数据的职员姓名:";
cin >> name;
//del(name);
for (int i = 0; i < num_count; i++) {
if (name == a[0][i]) {
for (int j = i; j < num_count; j++) {
a[0][j] = a[0][j + 1]; //依次用下一项替代这一项
a[1][j] = a[1][j + 1];
}
i--;
num_count--;
}
}
cout << "删除后的结果为:" << endl;
show();
return;
//return c[2][100];
}
void show()
{
//cout << "目前的职工的姓名和薪资为:" << endl;
for (int i = 0; i < num_count; i++)
cout << a[0][i] << " " << a[1][i] << endl;
cout << endl;
return;
}
void swap(int m)
{
string x = "";
string z = "";
x = a[0][m];
a[0][m] = a[0][m + 1];
a[0][m + 1] = x;
z = a[1][m];
a[1][m] = a[1][m + 1];
a[1][m + 1] = z;
return;
}
其中我觉得稍微有些复杂的地方就是string二维数组根据其中一维来排序。我是用最简单的冒泡排序来实现的,也就是依次比较每一个薪资和后一个人薪资的大小。这里我用到了一个格式转换函数stoi。
for (int i = 0; i < num_count - 1; i++) {
for (int m = 0; m < num_count - 1; m++) {
//if (strcmp(a[1][m] , a[1][m + 1])>0)
if (stoi(a[1][m], 0, 10) > stoi(a[1][m + 1], 0, 10)) //将string转换为int比较大小
swap(m);
}
}
stoi函数的用法参考了一下stoi函数 C++,需要用到标准库<string>。
还有这道题要注意同名职员都删除,所以每删除一个职员信息之后要i--。
for (int j = i; j < num_count; j++) {
a[0][j] = a[0][j + 1]; //依次用下一项替代这一项
a[1][j] = a[1][j + 1];
}
i--;
num_count--;
其他的就是一些C++的基础写法了。