【问题标题】:How to insert or push_back with unordered_mp of vectors如何使用 unordered_mp 向量插入或 push_back
【发布时间】:2019-08-27 02:51:52
【问题描述】:

我有一个数字向量:

nums = [2, 3, -2, 4]

我有一个std::unordered_map<int, std::vector<int>> m,我在其中迭代 nums 并计算连续乘积并插入索引对。

换句话说,我想从m得到这个

key  value
6  [0, 1]
-6  [1, 2]
-8  [2, 3]

我无法弄清楚如何实现这一目标。但这是我尝试过的:

#include <vector>
#include <iostream>
#include <unordered_map>

int main()
{
    std::vector<int> nums = {2, 3, -2, 4};
    std::unordered_map<int, std::vector<int>> m;
    int prod_max = INT_MAX;
    for(int i = 1; i < nums.size(); ++i)
    {
        prod_max = std::min(prod_max, nums[i-1]*nums[i]);
        m.at(prod_max).push_back({i-1, i});
    }

    for(auto it : m)
    {
        std::cout << it.first << "\n";
    }    
}

也许因为这不会导致编译器错误。我这样做是正确的,如果是这样,这将是一个更容易的问题:如何打印键和向量值?

【问题讨论】:

  • 我看不到 nums 与您的示例无序地图布局之间的关系。你能解释一下吗?
  • @ifconfig 你能澄清一下你的意思吗?我不确定。
  • 当然!我的问题是:nums 向量中的数据如何转换为您要填充到m 无序映射中的数据?
  • @ifconfig 是的,所以这可能会更支持leetcode.com/problems/maximum-product-subarray。我的想法是将 prod_max 存储为键并返回具有最大乘积的关联 nums。
  • 您应该专注于较小的问题,然后在较小的问题上构建更大的解决方案。您承认您的代码可能是正确的,因此您需要输出。如何打印键和向量值?好吧,如果你的地图是从intint,你能打印出键和整数值吗(即如何打印地图)?如果你有一个向量,你能打印出这个向量吗?如果你有这两个部分,你能把它们结合起来得到你想要的输出吗? [您需要以下哪些步骤的帮助?]

标签: c++ vector unordered-map


【解决方案1】:

您在这里尝试做的是将向量推送到向量。自从

m.at(prod_max)

给出一个 int 类型的向量,你不能将另一个向量推到它上面。正在做:

#include <vector>
#include <iostream>
#include <unordered_map>

int main()
{
    std::vector<int> nums = {2, 3, -2, 4};
    std::unordered_map<int, std::vector<int>> m;
    int prod_max = INT_MAX;
    for(int i = 1; i < nums.size(); ++i)
    {
        prod_max = std::min(prod_max, nums[i-1]*nums[i]);
        m[prod_max] = {i-1, i};
    }

    for(auto it : m)
    {
        std::cout << it.first << "\t";
        for(auto it2: it.second)
            std::cout << it2 << ",";
        std::cout << std::endl;
    }    
}

给我你想要的

编辑** 抱歉,我刚刚意识到您想要打印键和值。我已经更新了我的代码以反映这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2014-09-12
    • 2016-11-16
    • 2021-06-23
    • 2020-11-20
    相关资源
    最近更新 更多