简体   繁体   English

按字符串对结构数组排序

[英]Sort array of structs by string

I have this structure: 我有这个结构:

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;

and I'm trying to sort an array of that structure by cName, using this function: 并且我正在尝试使用以下函数通过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);
}

where iCantAgentes is amount of agents on the array, and agentesArr is the array. 其中,iCantAgentes是阵列上的代理数量,agentesArr是阵列。 For some reason, it's not working. 由于某种原因,它不起作用。 Can someone help me identify the problem please? 有人可以帮我找出问题吗?

Your function only sorts adjacent strings, not the whole array. 您的函数仅对相邻的字符串排序,而不对整个数组排序。 Try this: 尝试这个:

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;
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM