如何更新地图类型map <string,vector <int =“”>&gt;?

时间:2015-08-12 10:34:01

标签: c++ dictionary

我需要更新// 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; } 类型的地图。我创建了这个函数:

<span style='cursor:pointer' data-ng-class='highlightedText:true'>Dheepan raju</span>

我总是得到断言判断失败。

这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

您的断言将始终失败,因为如果在地图中找不到current_veckey将始终为空。我建议你删除这个临时向量,如果没有以其他方式找到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;
}

答案 1 :(得分:2)

如果我做对了,似乎只有在密钥确实存在时才会进行更新,因为更新代码只出现在if的正文中。

另一方面,仅当条件assert(即地图中存在关键字)不成立时才会检查it != d.end()(否则最终return语句在if正文中将导致函数结束)。

因此,当到达assert时,您知道current_vec.size()(因此prev_len)为0,因此断言会缩减为assert(1, 0),是假的。

作为旁注,由于您按值传递地图,因此您所做的更新不会反映在原始字典中。同样,请注意您还要将std::vector复制出地图。

相关问题