Użycie klasy do stworzenia tablicy rekordów

0

Witam, na zaliczenie muszę napisać program który będzie wyświetlał posortowaną tabelę najlepszych wyników zdobytych w grze. Do tego dostałem gotowe pliki nagłówkowe, które mam zaimplementować.
Oto one:
Record.h:

class Record {
private:
	string name;
	int score;

public:
	Record(string name, int score); //constr
	string toString() const; //changes the int to a string so you can easily cout using the branch[i].toString()

};

Record.cpp - napisałem go sam i nie wiem czy wszystko jest poprawnie

string Record::toString() const 
{
	string score_str = to_string(this->score);
	return score_str + " " + name;
}

Record::Record(string name = "Player", int score = 0)
{
	this->name=name;
	this->score = score;
}

ScoreTable.h:

class ScoreTable
{
private:
	Record* record;

public:
	Record* get(); //returns sorted records array (no need to implement it separately)
	Record append(string, int); //appends a record to the end of list(and returns this record)(Uses constructor of record)
	bool load(); //returns true when file is loaded
	bool save(); //use get() to save it in right order.
};

Problem polega na tym że nie wszystko potrafię zaimplementować i największy polega na wykorzystywaniu Record* record. Z tego co się orientuje ma to być dynamiczna tablica rekordów. Z tego co sam rozumiem mam wykorzystać te tablicę do zapisywania w niej rekordów z klasy rekord(czyli ma ona mieć zastosowanie podobne do struct) i w tej tablicy dokonywać sortowania itd. Czy ktoś mógłby mi pokazać jak jej używać pomiędzy funkcjami, tzn jak zapisać to w nawiasach deklaracji?

1

Spróbuj dodać implementacje operatora < do klasy Record , tak aby możliwe było sortowanie po wartości score.

 bool operator < (const Record& record) const
 {
      return (score<record.score);
 }

Następnie w klasie ScoreTable dodaj następujący set.

set<Record> records;

W apend implementujesz wstawianie do set, które to automatycznie sortuje elementy względem wartości score

void append( const Record& record )
{
   records.insert(record); 
} 
0

Po wstawieniuset<Record> recordsdo klasy ScoreTable pojawia się komunikat "incomplete type is not allowed" dla "records"

1

Nie jest to zbyt dobre rozwiązanie (w pracy odrzuciłbym coś takiego), ale z polecenia wynika, że masz stworzyć coś w rodzaju

int size = 16;  // jakaś początkowa wartość
int end = 0;
record = new Record[size];

Potem w append() musisz dbać o zwiększenie rozmiaru

record[end++] = Record(name, score);
if (end == size)
{
    size *= 2;
    Record *tmp = new Record[size];
    kopiuj_wszystko_z_record_do_tmp;
    delete[] record;
    record = tmp;
}

Do sortowania można używać std::sort (po zdefiniowaniu operator< lub używaniu własnego komparatora)

std::sort(record, record + size);

Warto pamiętać o delete[] record w destruktorze.

1 użytkowników online, w tym zalogowanych: 0, gości: 1