algorithm - Two conditions for find_if -
in std::vector<unsigned int>
, want find position of element maximum number smaller number. example:
v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
i want find number maximum smaller 8. number 7.
the following code not correct want get.
std::vector<unsigned int>::iterator pnt = std::find_if (v.begin(), v.end(), [](const unsigned int& x) { return x < 8; && x == max; });
if vector sorted, can in logarithmic complexity
auto = std::lower_bound(v.begin(), v.end(), 8); // first value >= 8 auto m = *((it != v.begin())? --it : it);
if vector unsorted, can modified, in 2 steps:
auto = std::partition(v.begin(), v.end(), [](int x) { x < 8 }); auto m = *(it != v.begin())? std::max_element(v.begin(), it) : it);
if can't modify vector, hand
auto max = 0; (elem: v) { if (elem < 8) m = std::max(elem, m); } // m max of elements < 8
both of 2 final approaches have linear complexity. latter can generalized using filter_iterator boost.iterator library, deep template land, if have repeated need such magic.
Comments
Post a Comment