1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
// Implement a sort function that takes a vector of pointers to an interface
// class, Comparable ,that defines a method, compare(Comparable& other) , and
// returns 0 if the objects are the same, 1 if the object is greater than
// other , and -1 if the object is less than other.
// Create a class that implements this interface, create several instances,
// and sort them.
// If you're looking for some inspiration for what to create—try a
// HighScoreElement class that has a name and a score, and sorts so that the
// top scores are first, but if two scores are the same, they are sorted
// next by name.
#include <iostream>
#include <vector>
// A base class with a pure virtual method (an abstract class)
class Comparable {
public:
Comparable(std::string n, int s);
virtual int compare(const Comparable& other) = 0;
// private: ?
std::string name;
int score {};
};
Comparable::Comparable(std::string n, int s)
/* omissis */
class HighScoreElement : public Comparable
{
public:
HighScoreElement(std::string n, int s);
int compare(const Comparable& other) override;
};
HighScoreElement::HighScoreElement(std::string n, int s)
/* omissis */
int HighScoreElement::compare(const Comparable& other)
{
if(score < other.score) { /* return proper value */}
else if(score == other.score) {
// omissis
// return proper value
}
// else if(score > other.score) <-- not needed, all cases already managed
// return proper value
}
// sort could also be a member function, but it's not required
std::vector<Comparable*> sort(std::vector<Comparable*> v);
int main()
{
std::vector<Comparable*> v;
for(int i{}; i< /* a value */; ++i) { // decide how many objects
v.push_back(new HighScoreElement("John Smith", 13));
// ...
}
for(const auto& e : v) { /* print unsorted vector */ }
sort(v);
for(const auto& e : v) { /* print sorted vector */ }
return 0;
}
std::vector<Comparable*> sort(std::vector<Comparable*> v)
{
// the worst part :)
}
|