I need a quick hint on this function. So basically I have this struct, used by a class.
#include <cstring>
#include <iostream>
using namespace std;
struct postazione{
char* nome;
bool occupato;
};
class Aula{
int qntpst;
postazione * vett;
bool full(const Aula&);
public:
Aula(int);
bool aggiungi(const char*);
friend ostream& operator<<(ostream&, const Aula&);
Aula& elimina(int);
Aula(const Aula&);
Aula& operator!();
~Aula();
};
That is, an array of which each element is a string and a bool, but the the last one is not important now.
The ! operator has to sort the array in alphabetical order.
Here's how I tried to do it.
Aula& Aula::operator!(){
int qnt=0;
for(int i=0;i<qntpst;i++)
if(vett[i].occupato)
qnt++;
if(qnt!=qntpst)
return *this;
char *temp;
for(int i=0;i<qntpst-1;i++){
for(int j=i+1;j<qntpst;j++){
if(strcmp(vett[i].nome,vett[j].nome)>0){
temp=new char[strlen(vett[i].nome)+1];
strcpy(vett[i].nome,temp);
delete [] vett[i].nome;
vett[i].nome=new char[strlen(vett[j].nome)+1];
strcpy(vett[i].nome,vett[j].nome);
delete [] vett[j].nome;
vett[j].nome=new char[strlen(temp)+1];
strcpy(vett[j].nome,temp);
delete temp;
}
}
}
return *this;
}
First 7 lines check if each bool of each element of the array is true, otherwise it won't execute. Then it starts to sort. That's how I tried to do it but it doesn't work.
P.S. The solution has to use an auxilary pointer, something like:
aux=i;
i=j;
j=aux;
qsortorstd::sort? You pass either one of them an array of whatever you like and provide a comparison function. (Your comparison function would essentially be a one-liner.)