c++ - 如何使用 STL 算法查找 2D 数组中列值的最大值和最小值

标签 c++ algorithm stl vector

我有一个 2D 数组(整数 vector 的 vector ),其中包含如下 int 值

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

最佳答案

创建一个比较特定列号的自定义仿函数,例如:

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

关于c++ - 如何使用 STL 算法查找 2D 数组中列值的最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6005961/

相关文章:

c++ - 使用 std::find_if 将迭代器传递给一元谓词

c++ - qt 5.7 + Xcode 8.1 + os x El Capitan - 无法解析 'macosx' 的 SDK 路径

c++ - 下面代码的算法复杂度是多少

algorithm - 使用 map reduce 使用 bfs 遍历图形的有效方法是什么?

图像变形 - 凸起效应算法

c++ - stm32f4 g++ 错误涉及newlib _kill_r,_kill, _getpid_r, _getpid,

c++ - 我怎样才能知道 13 号星期五在一年中出现了多少次?

c++ - make_heap 和排序 x 和 y 坐标

c++ - 带有自定义构造函数的自定义 STL 分配器

c++ - 具有调试功能的 C/C++ IDE 的建议