I wanted to convert the following function python to c :
def find_max_value(list):
max_value_list = []
for i in list:
max_value_list.append(i[0])
return max(max_value_list)
The inputs are the : [[90.272948, 210.999601, 90.31622, 349.000214, 4.042645], [520.293431, 349.000041, 520.285479, 211.000041, 2.007837], [237.026305, 263.076182, 237.629826, 247.023679, 4.523158]]
The Output is 520.293431.
I have tried but getting some errors. Could you please mention where I'm doing wrong?
std::list<int> find_max_value(std::list<int> a(std::list<double> b)){
std::list<int> max_value_list;
for (std::list<int>::iterator i = *a.begin(); i!=*a.end(); i){
max_value_list.push_back(i.front());
return std::max_element(i);
}
}
Thanks in advance!!!
CodePudding user response:
I'm going to guess you are looking for something like this:
double find_max_value(const std::list<std::list<double>>& a){
return std::max_element(a.begin(), a.end(),
[](const std::list<double>& lhs, const std::list<double>& rhs) {
return lhs.front() < rhs.front();
}
)->front();
}
This assumes none of the lists involved are empty.
CodePudding user response:
Note: This finds the max element in a list of lists as the title asked for. The python code however finds the max element of the first elements in the inner lists - which is what Igor's answer does.
You need a 2D std::list in order for your data to be stored in a similar way as in the python code. You can then use std::max_element on all the inner lists.
Example:
#include <algorithm>
#include <iostream>
#include <limits>
#include <list>
double find_max_value(const std::list<std::list<double>>& list) {
// start with the lowest possible double
double result = std::numeric_limits<double>::lowest();
for (auto& inner : list) {
if (!inner.empty())
result = std::max(result, *std::max_element(inner.begin(), inner.end()));
}
return result;
}
int main() {
std::list<std::list<double>> list{
{90.272948, 210.999601, 90.31622, 349.000214, 4.042645},
{520.293431, 349.000041, 520.285479, 211.000041, 2.007837},
{237.026305, 263.076182, 237.629826, 247.023679, 4.523158}};
std::cout << find_max_value(list) << '\n';
}
Output
520.293

