Created
June 8, 2022 10:25
-
-
Save aviralgoel/822a02a8a7d838eeab29097381be45ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
class Monster { | |
public: | |
int health; | |
int level; | |
char type; | |
Monster(int _h, int _l, char _c) { | |
health = _h; | |
level = _l; | |
type = _c; | |
} | |
}; | |
struct MonsterHealthSorter | |
{ | |
bool operator () (Monster m1, Monster m2) | |
{ | |
return m1.health < m2.health; | |
} | |
}; | |
struct MonsterTypeSorter | |
{ | |
bool operator () (Monster m1, Monster m2) | |
{ | |
return m1.type < m2.type; | |
} | |
}; | |
int main() | |
{ | |
vector<Monster> monsters = {Monster(100, 1, 'A'),Monster(50, 3, 'C'),Monster(400, 2, 'B')}; //default order | |
// printing the unsorted Monster array | |
for(int i = 0 ; i < monsters.size() ; i++) | |
{ | |
cout << monsters[i].health << " "; // output 100, 50, 400 (NOT sorted by health) | |
} | |
cout << endl; | |
sort(monsters.begin(), monsters.end(), MonsterHealthSorter()); | |
for(int i = 0 ; i < monsters.size() ; i++) | |
{ | |
cout << monsters[i].health << " "; // output 50, 100, 400 (sorted by health) | |
} | |
cout << endl; | |
sort(monsters.begin(), monsters.end(), MonsterTypeSorter()); | |
for(int i = 0 ; i < monsters.size() ; i++) | |
{ | |
cout << monsters[i].type << " "; // output A, B, C (sorted by type) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment