开发者

How to find max and min values of columns values in a 2D array using STL algorithms

开发者 https://www.devze.com 2023-03-05 19:00 出处:网络
I have a 2D array ( vector of vector of开发者_Python百科 ints ) with int values such as these 34198945

I have a 2D array ( vector of vector of开发者_Python百科 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


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号