如何在地图中添加值,并将向量作为值类型

How to add values in a map with a vector as a value type?

本文关键字:向量 类型 地图 添加      更新时间:2023-10-16

概述:我有一些代码可以遍历字符串(名称)列表以查找每个字符串的最后一个字符。我还有一个myGraph typedef映射,它将结构作为值类型。该结构包含向量节点下一个和向量next_cnt。

要做:每次在映射中插入新字符时,我需要将向量nextwt_vec初始化为空向量。

问题:使用以下代码,我的nextwt_vec保留了前一个字符的旧值。

    map<char, vector<int> > nextmap;

 for (myGraph::const_iterator j = graph.begin(); j != graph.end(); ++j)
 {
    vector<int> nextwt_vec;
    //populating next map with char and weighted ints
    for (int p=0; p< (int) (*j).second->nodenext.size(); ++p)
    {
        char cn = name[name.length() - 1];
        int wt = (*j).second->next_cnt[p];
        nextwt_vec.insert(nextwt_vec.begin()+p, wt);
        //puts char as key and weighted int as value in nextmap
        n->nextmap[cn] = nextwt_vec;
    }

输出:我得到的:

char: A   vec: 109 
char: C   vec: 109 vec: 48

我应该得到的输出:

char: A   vec: 109
char: C   vec: 48

感谢您的帮助!!

Drop vector nextwt_vec; 函数中的变量。直接使用 nextmap[cn].替换以下两行:

    nextwt_vec.insert(nextwt_vec.begin()+p, wt);
    //puts char as key and weighted int as value in nextmap
    n->nextmap[cn] = nextwt_vec;

有了这个:

    //puts char as key and weighted int as value in nextmap
    n->nextmap[cn].insert(nextwt_vec.begin()+p, wt);;