如何更新map<string, vector<int>>类型的映射
How to update maps of type map<string, vector<int>>?
我需要更新类型为map<string, vector<int>>
的映射。我创建了这个函数:
// INPUT: d - original map, key - key to be updated,
// new_val - value that will be appended to d[key]
// OUTPUT: vector<int> which is the updated value of d[key]
vector<int> update_value(map<string, vector<int>> d, string key, int new_val) {
map<string, vector<int>>::iterator it = d.find(key);
vector<int> current_vec;
int prev_len = current_vec.size();
if (it != d.end()) {
current_vec = it->second;
current_vec.push_back(new_val);
return current_vec;
}
assert(prev_len + 1, current_vec.size()); // this fails
return current_vec;
}
我总是得到断言语句失败。
正确的方法是什么?
您的断言将始终失败,因为current_vec
将始终是空的,万一在地图中没有找到key
。我建议您删除这个临时向量,如果没有以其他方式(例如插入)找到key
,您可以处理这种情况。
你还需要通过引用传递你的结构d
,以便它得到更新
vector<int>& update_value(map<string, vector<int>>& d, string key, int new_val) {
map<string, vector<int>>::iterator it = d.find(key);
if (it != d.end()) {
it->second.push_back(new_val);
}
else {
vector<int> v;
v.push_back(new_val);
d.insert(make_pair(key, v));
return d[key];
}
return it->second;
}
如果我做对了,似乎只有当键实际存在时才会发生更新,因为更新代码只存在于if
的主体中。
另一方面,assert
只在条件it != d.end()
(即键存在于映射中)不成立时才会被检查(否则if
体中的最后一条return
语句将导致函数结束)。
因此,当到达assert
时,您知道current_vec.size()
(因此prev_len
)是0
,因此断言减少到assert(1, 0)
,这是假的。
作为旁注,由于您是按值传递映射,因此您所做的更新将不会反映在原始字典中。同样,请注意,您也将std::vector
从地图中复制出来。
相关文章:
- 将 int 数组转换为 std::vector<int*>
- 使用 std::vector::reverse_iterator 将 int 序列化为字节向量?
- 从 std::vector<无符号字符>切片中提取 int?
- 如何创建一个类,以便向量工作 std::vector<MyClass<int>> v{ 1,2,3 };
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- int lastIndex[NO_OF_CHARS]={-1} 如何;不同于 vector<int> lastIndex(NO_OF_CHARS, -1);?
- 替代在python中制作邻接列表与图形问题的字典?(如 C++ 中的 vector<vector<int&g
- 将 vector<vector<int>> 传递到函数中会产生内存错误
- z3 提取 Seq Int 作为 std::vector<int>
- 警告级别为 3 的 int 的 std::vector push_back 处的编译器警告
- C++ std::vector<int> 体系结构的未定义符号 x86_64:
- 行 - " vector<int> used(adj.size(), 0); "是什么意思?
- C++"vector <int> adj[10]"候补出场
- 如何将 std::vector 索引交换到<int>数据,将数据交换到索引
- C++ - 如何使用<int> <int>STL 算法功能在矢量<vector>中找到矢量?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 代码中的"vector<<int>vector>&index"是什么意思?
- C# 等效于 C++ std::<int>vector.end()
- 尝试读取包含 ints 并存储在 int vector 中的文件,但我不断收到错误"Segmentation fault (core dumped)"
- 如何将 std::vector::emplace_back 与 vector<int><vector> 一起使用?