
C++ Coding Practice #3
Today's C++ coding practice is to find the maximum and minimum of two numbers without using any loop or condition.
The Code
Here's the implementation I whipped out in under 5 minutes:
This file contains hidden or 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> | |
int main() { | |
int a = 77; | |
int b = 5; | |
std::vector<int> v; | |
v.push_back(a); | |
v.push_back(b); | |
std::sort(v.begin(), v.end()); | |
std::cout | |
<< "Min = " << v[0] << std::endl | |
<< "Max = " << v[1] << std::endl; | |
} |
You can compile and run this code with the following commandline:
This file contains hidden or 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
$ g++ test.cpp && ./a.out | |
Min = 5 | |
Max = 77 |
Dev Notes
This file contains hidden or 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
// There may be a pedantic person out there that would argue: | |
// | |
// Internally, std::sort uses both loops and conditions | |
// | |
// but I think in practice, it's important to be creative and leverage | |
// external libraries and APIs. If this was a "just for fun challenge", then | |
// sure we can be overly strict, but in real life, this is not a | |
// practical constraint to impose 99.9% of the time. And this code does | |
// not directly use either loops or conditions. |