如何更新map<string, vector<int>>类型的映射

How to update maps of type map<string, vector<int>>?

本文关键字:int vector 何更新 类型 映射 string map 更新      更新时间:2023-10-16

我需要更新类型为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从地图中复制出来。

相关文章: