Vector sorting of character vectors with qsort <cstdlib>

Asked

Viewed 29 times

1

The following program is not ordering the chars vector correctly, but I don’t know why. Maybe it’s my auxiliary function "cmpstr" that isn’t returning the right value in some cases, or my qsort call... What’s wrong?

#include <iostream>
#include <cstdlib> //qsort
#include <cstring> //strcmp
using namespace std;

int cmpstr(const void* a, const void* b){ // função auxiliar do qsort
    const char* aa = (const char*)a;
    const char* bb = (const char*)b;
    return strcmp(aa, bb);
}

char equipe[1000][5000][50]; //array de arrays de arrays de caracteres

int main()
{
    int qtd_alunos, qtd_times, qtd_membros;
    cin>>qtd_alunos>>qtd_times;
    qtd_membros = qtd_alunos/qtd_times;

    for(int j=0; j<qtd_membros; j++){   //recebe nomes
        for(int i=0; i<qtd_times; i++){
            cin>>equipe[i][j];
        }
    }

    for(int j=0; j<qtd_times; j++){  //ordena cada equipe [deveria ordenar]
        qtd_membros = qtd_alunos/qtd_times;
        qsort(equipe[j], qtd_membros, sizeof(char*), cmpstr);
    }
    for(int i=0; i<qtd_times; i++){  //exibe a composição de cada equipe
        cout<<"Time "<<i+1<<'\n';
        qtd_membros = qtd_alunos/qtd_times;
        for(int j=0; j<qtd_membros;j++){
            cout<<equipe[i][j]<<'\n';
        }
        cout<<'\n';
    }
    return 0;
}

1 answer

1

Maybe it’s not the answer you want, but I’ll give you the best solution.

You’re using C++, right? Then use C++. Don’t use C. If you didn’t know this difference, you’re learning it now. If someone told you to do it like that, you better start listening to other people.

Use sort in place of qsort. Then take it and use it vector in place of array, or at least array. It may already solve your problem. If this does not occur, at least you can ask a question on a good code base.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.