c++ 二維string數組對於職工姓名薪金數據的存放、排序、刪除操作

昨天我的一個上財的同學發來一道作業題讓我提供思路,也算是幫我複習了一下二維數組包括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++的基礎寫法了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章