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

后端 未结 1 566
攒了一身酷
攒了一身酷 2021-01-22 08:27

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

1条回答
  •  天涯浪人
    2021-01-22 08:48

    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 & lhs, const std::vector & rhs) const
        {
            return lhs[column_num] < rhs[column_num];
        }
    };
    
    ...
    
    std::vector> 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 讨论(0)
提交回复
热议问题