Let us assume we have a vector of vectors and wish to find a minimum (or maximum) values (no need to know their position in the table). What would be an elegant way to accomplish this?
The obvious solution, included below, is to run std::min_element per each row in a loop. But may be it is possible to do it with a single statement without loop using, may be, lambda functions?
Note, there is a similar question on SO already, but it is actually not quite about what I am asking here.
Update: Ideal solution would be using STL only, but, failing that, it would be interesting to see other options.
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<double> > test_array=
{
{1., 2., 3., 4.},
{7., 4., 6., 8.},
{5., -1., 3., 1}
};
double min_val(test_array[0][0]);
double max_val(test_array[0][0]);
for(auto& row : test_array)
{
min_val = std::min(min_val, *std::min_element(row.begin(), row.end()));
max_val = std::max(max_val, *std::max_element(row.begin(), row.end()));
}
cout << "Minimum = " << min_val << std::endl;
cout << "Maximum = " << max_val << std::endl;
return 0;
}
std::max_element(begin(array), end(array), 0, [](){})because you would need to return an iterator on a vector, and not on an element :/ranges::view::jointo see the range of ranges as flattened range, then a simplestd::minmax_elementwould be sufficient.