gpt4 book ai didi

c - 按字符串对结构体数组进行排序

转载 作者:行者123 更新时间:2023-11-30 16:35:23 25 4
gpt4 key购买 nike

我有这样的结构:

struct agente {
int iCode;
char cName[21];
char cLName[21];
char cAgentID[16];
char cAssets[5][35];
int iContAssets;
int iAge;
char cGender;
char cMission[5][13];
int iContMisiones;
};

typedef struct agente agente;

我正在尝试使用此函数按 cName 对该结构的数组进行排序:

void sortAgents(agente* agentesArr, int iCantAgentes) {
int didSwap = 0;
agente temp;

do {
didSwap = 0;
for(int i = 0; i < iCantAgentes - 1; i++) {
int comp = strcmp(agentesArr[i].cName, agentesArr[i+1].cName);
if(comp > 0 ) {
temp = agentesArr[i];
agentesArr[i] = agentesArr[i+1];
agentesArr[i+1] = temp;
didSwap = 1;
}
}
} while(didSwap == 1);
}

其中 iCantAgentes 是阵列上的代理数量,agentesArr 是阵列。由于某种原因,它不起作用。有人可以帮我找出问题所在吗?

最佳答案

您的函数仅对相邻字符串进行排序,而不对整个数组进行排序。试试这个:

void sortAgents(agente* agentesArr, int iCantAgentes) {
agente temp;

for(int i = 0; i < iCantAgentes - 1; i++) {
for(int j=i+1; j < iCantAgentes - 1; j++){
int comp = strcmp(agentesArr[i].cName, agentesArr[j].cName);
if(comp > 0) {
temp = agentesArr[i];
agentesArr[i] = agentesArr[j];
agentesArr[j] = temp;
}
}
}
}

关于c - 按字符串对结构体数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com