如何插入或push_back unordered_mp载体

How to insert or push_back with unordered_mp of vectors

本文关键字:back unordered mp 载体 push 何插入 插入      更新时间:2023-10-16

我有一个数字向量:

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

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

换句话说,我希望从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";
}    
}

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

你在这里要做的是将一个向量推送到一个向量。因为

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

给我你想要的

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