-2

重複の可能性:
プライベートで宣言された整数をソートする方法

クラス内の 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;
 };
4

1 に答える 1

0

一般的な手法は、比較可能なクラスに対して比較演算子 <、>、<=、>=、==、および != を提供することです。ほとんどの並べ替えアルゴリズムでは、コンテナ内のアイテムが「比較可能ではない」ことが必要です。

Boost ライブラリを参照してください。これには、より小と等号のみが定義されている場合にすべての比較演算子を定義するツールが含まれています。

設計では、s のコンテナーが必要になりますstudentstd::sortまたはコンテナで好みのソート機能を使用します。これが宿題である場合はmain()、並べ替えロジックと共にコンテナーを配置することをお勧めします。

また、Web で「C++ オーバーロード演算子」を検索するか、独自のメソッドを定義してください。賢ければ、さまざまなフィールドでソートできるように、さまざまな比較関数を持つようにクラスを設計できます。

于 2012-05-01T13:29:02.833 に答える