2012-05-01 21 views
-2

可能重複:
how to sort an integer that is declared in the private排序類的私有元素

我有關於如何在類中的int id元素進行排序的麻煩, 這裏是在那裏我會把我的功能爲類

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

#include "student.h" 
#define cap 100 

//Student constructor- empty 

student::student() 
{ 
    id = 0; 
    first = "null"; 
    last = "null"; 
    age = 0; 
    gpa = 0.0; 
} 

//Student deconstructor 

student::~student() 
{ 

} 

bool student::get(istream &in) 
{ 

    in >> id >> first >> last >> age >> gpa; 
    return(in.good()); 
} 
void student::put(ostream &out) 
{ 
    out << id << first << last << age << gpa; 
} 
bool student::operator>(student) 
{ 
    if(student[i].id>student[i+1].id) 
     return true; 
    else 
     return false; 
    cout << student[i].id; 
} 

bool student::operator<(student) 
{ 
    if(student[i].id<student[i+1].id) 
     return true; 
    else 
     return false; 
} 
void student::sort_array() 
{ 

    int j,temp; 
    for(j=0;j<cap-1;j++) 
    { 
//if out of position switch the out of align number 
    if(student[i].id<student[i+1].id) 
     { 
      temp = student[i].id; 
      student[i].id = student[i+1].id; 
      student[i+1].id = temp; 
     } 
    } 
} 

這是我的文件,我的主要代碼將顯示和調用函數

#include <iostream> 
#include <fstream> 
#include <string> 
#include <iomanip> 
using namespace std; 

#include "student.h" 
#define cap 100 
void main() 
{  string s; 
    class student student[cap],l; 
    int i; 
    fstream f; 

    i=0; 
    cout << "Enter the file name: "; //Display to enter the file name 
    cin >>s; 


    f.open(s.data(),ios::in); 
    if(!f.is_open()) 
     cout << "could not open file"; 
    while(i<cap && !f.eof()) 
    { 
     student[i].get(f); 

//Display if okay 
     if(f.good()) 
     { 
      student[i].sort_array(); 
      i++; 
      cout << i; 
     } 
    } 
    f.close(); 
} 

這是我的類代碼,並類文件

#include <iostream> 
using namespace std; 

class student 
{ 
    public: 
     student(); //Constructor without parameters 
     student(int,string,string,int,float); //Constructor with parameters 
     ~student(); //Deconstructors 
     bool get(istream &); //Input 
     void put(ostream &); //Output 
     bool operator==(student); 
     bool operator>(student); 
     bool operator<(student); 
     bool operator==(int); 
     bool operator>(int); 
     bool operator<(int);  
     int read_array(string,int); 
     void sort_array(); 
    private: 
     int id,age; 
     float gpa; 
     string last,first; 
}; 
+2

需要'家庭作業'標籤嗎? –

+0

你似乎混淆了你的班級,學生和一羣學生。 – Chowlett

+2

您無法對單個元素進行排序。 – juanchopanza

回答

0

的常用技術是提供比較運算符,<,>,< =,> =,==和!=,可以比較的類。大多數排序算法要求容器中的項目可以「少於可比」。

查找Boost庫,因爲它具有定義所有比較運算符的工具,當只定義了小於等於相等值時。

在您的設計中,您將需要一個容器,用於您的student s。使用std::sort或您在容器上的首選分類功能。如果這是作業,您可能希望將容器與排序邏輯一起放入main()

此外,要麼搜索網絡的「C++重載操作符」或定義自己的方法。如果你聰明,你可以設計你的班級有不同的比較功能,以允許不同領域的排序。