Skip to content

Instantly share code, notes, and snippets.

@Frontear
Last active October 9, 2020 14:38
Show Gist options
  • Select an option

  • Save Frontear/8506588394df699ed536b99c296f736f to your computer and use it in GitHub Desktop.

Select an option

Save Frontear/8506588394df699ed536b99c296f736f to your computer and use it in GitHub Desktop.
Programming technique to compare objects inside of a loop without needing to loop twice
#include <iostream>
// find the max value in an array
int main() {
int array[] = { 11, 100, 99, 95, 14, 62, 35, 74 };
auto j = 0u;
for (auto i = 0u; i < 8; ++i) {
if (array[j] < array[i]) { // controls comparisions to find the maximum value without needing to loop the same array twice
j = i;
}
}
// by this point, array[j] is guaranteed to be the maximum value
std::cout << array[j] << std::endl;
return 0;
}
@Frontear

Frontear commented Oct 9, 2020

Copy link
Copy Markdown
Author

You can easily switch this to find the minimum value. It's not particularly complicated as a code piece, however you may find value in being reminded of this, as its not the most obvious solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment