我需要對此函數進行快速提示。所以基本上我有這個結構,由一個類使用。對字符串數組進行排序
#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();
};
即,陣列的每個元素是一個字符串和一個bool,但最後一個現在並不重要。
這個!運算符必須按字母順序對數組進行排序。
下面是我試圖做到這一點。
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;
}
首先7行檢查,如果該數組的每個元素的每個布爾爲真,否則將不會執行。然後它開始排序。 這就是我試圖做到這一點,但它不起作用。
P.S.解決方案必須使用輔助指針,如下所示: aux=i; i=j; j=aux;
歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)適用於此處。在您發佈代碼並準確描述問題之前,我們無法有效幫助您。 特別是,「不起作用」不是對問題的描述。顯示給定的輸入和輸出。 – Prune
gawd almighty。任何不使用'qsort'或'std :: sort'的理由?您可以將其中任何一個傳遞給您喜歡的任何數組,並提供比較功能。 (你的比較函數本質上是一行代碼。) – enhzflep
我知道你們所有人都認爲我應該使用它,事實是,這整個事情都是我昨天的C++考試,這就是爲什麼我使用!運算符來排序數組,因爲它被要求我這樣做。現在我必須糾正任何我無法實現的功能。 – user5753059