如何插入或push_back unordered_mp载体
How to insert or push_back with unordered_mp of vectors
我有一个数字向量:
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;
}
}
给我你想要的
编辑** 抱歉,我刚刚意识到您希望同时打印键和值。我已经更新了我的代码以反映这一点。
相关文章:
- 推导 std::vector::back() 的返回类型
- vector.back() 和 vector[vector.size() - 1] 之间的区别?
- vector.push_back(vector.back()+1) 是未定义的行为吗?
- 线路抑制状态错误 C4703 可能未初始化的局部指针变量"back"已使用
- std::vector using back(), pop_back(), push_back(), 得到'double free or corruption'错误
- vector.back()和vector.end()有什么区别
- 列表大小为 1,但 front() 和 back() 不相等
- 返回C++中没有 back() 方法的容器的最后一个元素?
- 在非空 std::list 上使用 std::list.back<int>() 时"Segmentation Fault"
- 我们可以使用Back() - 值索引在其上执行向量插入
- 当我运行以下代码添加str.front() str.back时,它给了我200个,但为什么
- 链表回推操作中需要'back pointer'
- 为什么 std::string 的 back() 应该返回对字符的引用?
- VC++ 自动说明符假定矢量的引用限定符<bool>::back的引用限定符
- 是否可以<int>在一行中将向量值分配给 std::unordered<int,std::vector<int>>?
- C: strtok value gives back null
- vector.back() 可以用来为向量的最后一个元素赋值吗?
- 在std::vector中实现back()
- 在push_front属性上有点混淆.intlist.push_front(2 * intlist.back())会做些
- 将对象转换为 char,然后"uncasting it back"