【问题标题】:How to find max and min values of columns values in a 2D array using STL algorithms如何使用 STL 算法在二维数组中查找列值的最大值和最小值
【发布时间】:2011-05-15 01:41:24
【问题描述】:

我有一个带有 int 值的二维数组(向量的 ints 向量),例如这些

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

我想找到列值(不是行值)的最大值和最小值 最好使用 STL 算法

std::max_element, std::min_element

【问题讨论】:

  • 是行向量还是列向量?这显然很重要。
  • 列值的最大值是什么意思?列总和的最大值还是列最大值的向量?

标签: c++ algorithm stl vector


【解决方案1】:

创建一个比较某个列号的自定义函子,例如:

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

【讨论】:

  • 快速提示:您需要在 std::vector&lt;int&gt;v 的声明中的 ">" 字符之后添加一个额外的空格才能编译,除非您使用 C+ +0x。
猜你喜欢
  • 2019-03-31
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
  • 2018-09-14
  • 2017-03-16
相关资源
最近更新 更多