【问题标题】:loop over map of vectors and get max across columns in c++遍历向量图并在c ++中跨列获取最大值
【发布时间】:2021-05-07 02:38:47
【问题描述】:

我的地图定义如下:

const map<int, vector<float> >& m = …;

我想遍历列(map.second: 向量的大小)并且在每次迭代中我得到:

1- 跨地图列的最大值。first: int

2- map.first 的值:最大值出现的 int

例如:

#0 我得到 31, 1

#1 我得到 15, 2

#2 我得到 18, 2

最简单的方法是什么?

【问题讨论】:

  • 你尝试了什么?
  • 你应该考虑在这个问题中提供你的编码工作。
  • 欺骗关闭是错误的,对此感到抱歉。我已经重新打开了。
  • 所有向量的大小是否相同或可以变化?
  • 这样的东西怎么样:onlinegdb.com/Yd7yn5cJU

标签: c++ dictionary max


【解决方案1】:

您需要一个函数,该函数接受列号并遍历每一行,计算该列的最大值。

您只需要一个循环,因为您可以通过像数组一样对向量进行索引来访问您想要的任何列(只要您检查向量是否有足够的元素)

有两种方法可以做到这一点:C++17 方法,您可以将具有多个值的对象直接分配给多个变量,以及引用 std::pair 成员的旧方法。

C++17 方式:

#include <map>
#include <vector>
#include <utility>
#include <iostream>

std::pair<int,float> column_max(const auto & m, int column)
{
    int index = -1;
    float maximum = -std::numeric_limits<float>::max();
    for (const auto & [key,value] : m)
        if (value.size() > column && value[column] > maximum)
        {
            index = key;
            maximum = value[column];
        }
    return {index,maximum};
}


int main()
{
    const std::map<int,std::vector<float>> m =
    {
        {0, { 1,  5, 10, 22}},
        {1, {31,  5, 10, 12}},
        {2, { 1, 15, 18, 12}}
    };

    for (int i=0; i<4; i++)
    {
        const auto [index,maximum] = column_max(m,i);
        std::cout << "#" << i << ": " << maximum << " " << index << "\n";
    }
    
    return 0;
}

在这里试试:https://onlinegdb.com/O5dmPot34

等价的,但更旧的方式:

#include <map>
#include <vector>
#include <utility>
#include <iostream>
#include <float.h>

std::pair<int,float> column_max(const std::map<int,std::vector<float>> & m, int column)
{
    int index = -1;
    float maximum = -FLT_MAX;
    for (std::map<int,std::vector<float>>::const_iterator entry=m.begin(); entry!=m.end(); entry++)
        if (entry->second.size() > column && entry->second[column] > maximum)
        {
            index = entry->first;
            maximum = entry->second[column];
        }
    return std::make_pair(index,maximum);
}


int main()
{
    const std::map<int,std::vector<float>> m =
    {
        {0, { 1,  5, 10, 22}},
        {1, {31,  5, 10, 12}},
        {2, { 1, 15, 18, 12}}
    };

    for (int i=0; i<4; i++)
    {
        std::pair<int,float> value = column_max(m,i);
        std::cout << "#" << i << ": " << value.second << " " << value.first << "\n";
    }
    
    return 0;
}

在这里试试:https://onlinegdb.com/273dnHRZK

【讨论】:

    猜你喜欢
    • 2015-09-21
    • 2016-11-28
    • 1970-01-01
    • 2013-11-08
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    相关资源
    最近更新 更多