Last active
February 15, 2016 08:14
-
-
Save ilpropheta/4ef3b7264516c5d9b27f to your computer and use it in GitHub Desktop.
Replacing if-cascade on numerical ranges with 3-LOC (using vector + upper_bound)
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 <algorithm> | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
/* | |
Just for fun: equivalent to: | |
if (score < 40) | |
return 'D'; | |
if (score >= 40 && score<60) | |
return 'B'; | |
if (score >= 60 && score<75) | |
return 'A'; | |
if (score >= 75 && score<90) | |
return 'E'; | |
return 'O'; | |
*/ | |
char grade(int score) | |
{ | |
static const vector<int> ranges{40, 60, 75, 90, 100}; | |
static const vector<char> grades{'D', 'B', 'A', 'E', 'O', 'O'}; // last 'O' is kind of "saturation" | |
return grades[distance(begin(ranges), upper_bound(begin(ranges), end(ranges), score))]; | |
} | |
int main() | |
{ | |
cout << grade(0) << endl; // D | |
cout << grade(45) << endl; // B | |
cout << grade(60) << endl; // A | |
cout << grade(100) << endl; // O | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment