#include <vector>#include <iostream>struct Point{ double x, y, z;};double dot(const Point& a, const Point& b){ return a.x * b.x + a.y * b.y + a.z * b.z;}int main(){ // data to process std::vector<Point> points = { {0, 0, 0}, {1, 2, 3}, {-1, -2, 5} }; // context for cost function Point dir{0, 1, 0}; // cost function is lambda wich captures some context // computationally expensive should not be called several times for same element auto cost = [&](const Point& p) { return dot(dir, p); }; // we need to find index of point with maximal cost size_t index = 0; double maxCost = cost(points[index]); for (size_t i = 0; i < points.size(); ++i) { double c = cost(points[i]); if (maxCost < c) { maxCost = c; index = i; } } std::cout << "Index of point with maximal cost: " << index << std::endl; // how can this be written with stl/boost algorithms?}
auto iter = boost::max_element(points | boost::adaptors::transformed(cost));
C++ (Qt)template <class It, class UnaryFunction>It qmax_element(It first, It last, UnaryFunction f){ auto max = f(*first); It it = first++; for (; first != last; ++first) { auto val = f(*first); if (val > max) { max = val; it = first; } } return it;}
C++ (Qt) std::vector<int> v = {21, 3434222, 3, -10, -4, 101, 5}; auto max = cost(v[0]); auto it = std::max_element(v.begin(), v.end(), [&max](int, int x)->bool { auto val = cost(x); bool res = val > max; if (res) max = val; return res; });
C++ (Qt) auto points_costs = ranges::view::transform(points, cost); auto index = ranges::distance(points_costs.begin(), ranges::max_element(points_costs));