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:

#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;
}
view raw test.cpp hosted with ❤ by GitHub

You can compile and run this code with the following commandline:

$ g++ test.cpp && ./a.out
Min = 5
Max = 77
view raw commandline.txt hosted with ❤ by GitHub

Dev Notes

// 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.
view raw dev-notes.cpp hosted with ❤ by GitHub

Explore More