004
18.08.2005, 11:07 Uhr
virtual
Sexiest Bit alive (Operator)
|
Ich würde nicht lange fakeln und ein Highscore als ein Set von Highscore_entries auffasssen, dafür entsprechende Eingabe- ausgabe- und Vergleichsroutien definieren. Der Rest ist dann ein kinderpsiel:
Im folgenden Benötigte Includes:
C++: |
#include <iostream> #include <string> #include <set> #include <fstream>
|
Klasse, die einen Highscoreeintrag abbildet:
C++: |
class highscore_entry { private: std::string player; unsigned score;
public: highscore_entry(const std::string& player_ = "", unsigned score_ = 0) :player(player_), score(score_) { } const std::string& get_player() const { return player; } unsigned get_score() const { return score; } void set_player(const std::string& player_) { player = player_; } void set_score(unsigned score_) { score = score_; } };
bool operator < (const highscore_entry& a, const highscore_entry& b) { return a.get_score() < b.get_score(); }
std::ostream& operator << (std::ostream& out, const highscore_entry& entry) { out<<entry.get_score()<<'/'<<entry.get_player()<<std::endl; return out; }
std::istream& operator >> (std::istream& in, highscore_entry& entry) { unsigned score; std::string player; in>>score; in.ignore(1); getline(in, player); entry.set_player(player); entry.set_score(score); return in; }
|
Klasse die einen Highscore abbildet, nur Grundgerüst, aber Funktionokkelnd:
C++: |
class highscore {
std::set<highscore_entry, std::greater<highscore_entry> > entries;
public: typedef std::set<highscore_entry, std::greater<highscore_entry> >::const_iterator const_iterator; typedef std::set<highscore_entry, , std::greater<highscore_entry> >::iterator iterator;
void insert(const highscore_entry& entry) { entries.insert(entry); while (entries.size()>10) { // Behält max. 10 Einträge im Highscore entries.erase(*entries.rbegin());
} }
const_iterator begin() const { return entries.begin(); }
const iterator end() const { return entries.end(); }
iterator begin() { return entries.begin(); }
iterator end() { return entries.end(); } };
std::ostream& operator << (std::ostream& out, const highscore& highscore) { for(highscore::iterator i=highscore.begin(); i!=highscore.end(); ++i) { out<<*i; } return out; }
std::istream& operator >> (std::istream& in, highscore& highscore) { do { highscore_entry entry; if (in>>entry) highscore.insert(entry); } while (in); return in; }
|
Anwendung:
C++: |
int main() { highscore h;
// Einlesen hightscore std::ifstream in("highscore.txt"); if (in) { in>>h; } in.close();
// Neuen Eintag einfügen. std::cout<<"Bitte Punkte/Spieler eingeben, (also zB: 7/Player A): "<<std::endl; highscore_entry entry; std::cin>>entry; h.insert(entry);
// Highscore wegschreiben std::ofstream out("highscore.txt"); out<<h;
// Highscore ausgeben std::cout<<"Der Highscore momentan: "<<std::endl <<h; }
|
-- Gruß, virtual Quote of the Month Ich eß' nur was ein Gesicht hat (Creme 21) |