如何插入 or push_back with unordered_mp 向量

How to insert or push_back with unordered_mp of vectors

我有一个 nums 向量:

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";
    }    
}

可能是因为这不会导致编译器错误。我这样做是正确的,如果是这样的话,这将更容易成为一个问题:How do I print the keys and the vector values?

您在这里要做的是将一个向量推到另一个向量。自

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

给你想要的

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