How to find max and min values of columns values i

2019-02-26 07:47发布

问题:

I have a 2D array ( vector of vector of ints ) with int values such as these

34  19  89  45
21  34  67  32
87  12  23  18

I want to find a max and min value for the column values ( not row values ) preferably using the STL algorithms

std::max_element, std::min_element

回答1:

Create a custom functor that compares a certain column number, e.g.:

struct column_comparer
{
    int column_num;
    column_comparer(int c) : column_num(c) {}

    bool operator()(const std::vector<int> & lhs, const std::vector<int> & rhs) const
    {
        return lhs[column_num] < rhs[column_num];
    }
};

...

std::vector<std::vector<int>> v;
...
... // fill it with data
...
int column_num = 3;
int n = (*std::max_element(v.begin(), v.end(), column_comparer(column_num)))[column_num];