简体   繁体   中英

Finding Max element of the list of lists in c++ (conversion of python function)

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)

Note: This finds the max element in a list of lists as the title asked for.<\/sup> The python code however finds the max element of the first elements in the inner lists - which is what Igor's answer<\/a> does.<\/sup>

You can then use

#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';
}

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM