C语言结构体数组:增删查排序实现示例
#include <stdio.h>
#define MAX_SIZE 100
typedef enum {Alice, Bob, Charlie, David, Emily} Name;
typedef struct { Name name; float amount; int index; } Money;
typedef struct { Money list[MAX_SIZE]; int size; } MoneyList;
void Find_num(MoneyList *ml, int _num) { for (int i = 0; i < ml->size; i++) { if (ml->list[i].index == _num) { printf("Name: %d, Amount: %.2f\n", ml->list[i].name, ml->list[i].amount); return; } } printf("No record found with index %d\n", _num); }
void delete_num(MoneyList *ml, int _num) { for (int i = 0; i < ml->size; i++) { if (ml->list[i].index == _num) { for (int j = i; j < ml->size - 1; j++) { ml->list[j] = ml->list[j + 1]; ml->list[j].index--; } ml->size--; printf("Record with index %d deleted\n", _num); return; } } printf("No record found with index %d\n", _num); }
void sort_by_amount(MoneyList *ml) { for (int i = 0; i < ml->size - 1; i++) { for (int j = 0; j < ml->size - i - 1; j++) { if (ml->list[j].amount > ml->list[j + 1].amount) { Money temp = ml->list[j]; ml->list[j] = ml->list[j + 1]; ml->list[j + 1] = temp; } } } printf("Sorted by amount\n"); }
int main() { MoneyList ml; ml.size = 0;
Money m1 = {Alice, 100.0, 0}; ml.list[ml.size++] = m1;
Money m2 = {Bob, 200.0, 1}; ml.list[ml.size++] = m2;
Money m3 = {Charlie, 150.0, 2}; ml.list[ml.size++] = m3;
Find_num(&ml, 2); delete_num(&ml, 1); sort_by_amount(&ml);
return 0; }
原文地址: https://www.cveoy.top/t/topic/p3Yv 著作权归作者所有。请勿转载和采集!