【问题标题】:How to add values in a map with a vector as a value type?如何在带有向量作为值类型的地图中添加值?
【发布时间】:2012-10-10 23:30:33
【问题描述】:

概述:我有一些代码遍历字符串列表(名称)以查找每个字符串的最后一个字符。我还有一个 myGraph typedef 映射,它接受一个结构作为值类型。该结构体包含向量 nodeext 和向量 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

感谢您的帮助!!

【问题讨论】:

  • 将声明 vector&lt;int&gt; nextwt_vec; 移入 for 循环中。
  • 我不明白。你在哪里输出文本? char: C vec: 109 vec: 48 是什么意思?
  • @KerrekSB 当我这样做时,我得到一个分段错误:11 错误

标签: c++ stl map vector


【解决方案1】:

下降向量 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);;

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2010-12-18
    相关资源
    最近更新 更多