Home:ALL Converter>How can I find the minimum key value from an std::vector of std::map values?

How can I find the minimum key value from an std::vector of std::map values?

Ask Time:2016-05-08T07:45:20         Author:Chad Johnson

Json Formatter

I have an std::vector of std::map values:

std::vector<std::map<std::string, double>> dataPoints;

I would like to find the lowest low value, 74.0. Here is my application so far:

#include <vector>
#include <map>
#include <iostream>

int main() {
    std::vector<std::map<std::string, double>> dataPoints;

    dataPoints.push_back({{{"high", 77.0}, {"low", 74.0}}});
    dataPoints.push_back({{{"high", 78.0}, {"low", 75.0}}});
    dataPoints.push_back({{{"high", 79.0}, {"low", 76.0}}});
    dataPoints.push_back({{{"high", 80.0}, {"low", 77.0}}});
    dataPoints.push_back({{{"high", 81.0}, {"low", 78.0}}});

    return 0;
}

The closest I have found so far is:

double min = std::min_element(dataPoints.begin(), dataPoints.end(), [](std::map<std::string, double> &a, std::map<std::string, double> &b) { return (a["low"] < b["low"]); })["low"];

But this does not quite work.

In JavaScript, I could achieve this as follows:

low = _.min(_.map(dataSegment, function(dataPoints) {
    return dataPoint.low;
}));

Author:Chad Johnson,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/37094791/how-can-i-find-the-minimum-key-value-from-an-stdvector-of-stdmap-values
T.C. :

You want min_element, not max_element. And it returns an iterator so you'll want to dereference it.\n\nAnd I suppose you probably don't want to insert a zero if \"low\" is not in the map. So at instead of []; this also allows us to constify the whole thing across the board.\n\ndouble min = std::min_element(dataPoints.cbegin(), dataPoints.cend(),\n [](const std::map<std::string, double> &a,\n const std::map<std::string, double> &b) {\n return a.at(\"low\") < b.at(\"low\"); \n })->at(\"low\");\n",
2016-05-07T23:51:24
yy