LoginSignup
3
2

More than 5 years have passed since last update.

std::min_elementで0でない最小値を見つけるための比較関数

Posted at

min_element内部では

min_element
if (comp(*first, *smallest)) {
  smallest = first;
}

なので,
*firstが0のときにfalse,
*secondが0のときにtrueを返せばOK.

min.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using std::cout;
using std::endl;
int main() {
  vector<int> a = {0, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 0};
  auto min = min_element(a.begin(), a.end(), [](int a, int b) {
      return (a == 0) ? false : (b == 0) || a < b;
    });
  cout << *min << endl;
  return 0;
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2