Skip to content

Instantly share code, notes, and snippets.

@ilpropheta
Last active February 15, 2016 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilpropheta/4ef3b7264516c5d9b27f to your computer and use it in GitHub Desktop.
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)
#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