Vector sorting of character vectors with qsort
The following program is not ordering the vector of chars vectors correctly, but I don't know why. Maybe it's my helper function "cmpstr" that is not 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
Author: Carlos Mendes, 2016-06-16
1 answers
May not be the answer you want, but I will give the one that is and best solution.
Is using C++, right? Then use C++. Do not use C. If you did not know this difference, you are learning now. If someone told you to do this, better start listening to other people.
Use sort
in place of qsort
. Then enjoy and use vector
instead 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 top of a good code base.
1
Author: Maniero, 2016-06-16 04:18:33