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

后端 未结 1 563
攒了一身酷
攒了一身酷 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<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 讨论(0)
提交回复
热议问题