【问题标题】:unordered_map insertion failsunordered_map 插入失败
【发布时间】:2017-02-14 14:37:52
【问题描述】:

注意:我花了很多时间试图了解我的问题出在哪里。但是,当我写这篇文章时,我找到了解决问题的方法。然而,我认为它仍然值得发布。此外,我不能 100% 确定我的解释。


这是我的一个简单示例的简化问题。

matrix二元矩阵 的稀疏表示。在这个例子中我选择了:

1 0
1 1
0 0
1 1

每一列都由set<int> 表示,给出非零元素的索引。例如,对于矩阵的第一列,索引 {0,1,3} 的行不为零。

算法目标

  • 对于每一列,找到该列的最高索引(例如,第一列是 3),查看highestMapToColumns unordered_map 中是否有某列已插入
  • 然后如果找到一个列,则对该列执行一些操作。不过,为了清楚起见,这里没有执行任何操作。
  • 最后,将(highestIndex,column) 对添加到无序映射highestMapToColumns

`

// main.cpp
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <unordered_map>

using namespace std;

int main(int argc, char** argv) {

    vector<set<int>* >* matrix = new vector<set<int>* >();
    int column1[]= {0,1,3};
    int column2[]= {1,3};
    matrix->push_back(new set<int>(column1,column1+3));
    matrix->push_back(new set<int>(column2,column2+2));

    unordered_map<int, set<int>* > highestMapToColumns;
    int highestIndex = -1;
    for(vector<set<int>* >::iterator iteratorOnColumns = matrix->begin();iteratorOnColumns!=matrix->end();iteratorOnColumns++){
        while(true){
            if((*iteratorOnColumns)->size() == 0){
                highestIndex = -1;
                break;
            }
            highestIndex = *((*iteratorOnColumns)->rbegin());
            cout<<"Attempting to get index : "<<highestIndex<<endl;
            set<int>* toSubstract = highestMapToColumns[highestIndex];
            if (toSubstract != nullptr) {
                cout<<"Column found !!"<<endl;
                break;
            }else{ 
                cout<<"Column not found"<<endl;
                break;
            }
        }
        if(highestIndex != -1){
            cout<<"Attempting to insert index : "<<highestIndex<<endl;
            highestMapToColumns.insert(make_pair(highestIndex, (*iteratorOnColumns)));
        }
    }
    return 0;
}
此程序的

输出

Attempting to get index : 3
Column not found
Attempting to insert index : 3
Attempting to get index : 3
Column not found
Attempting to insert index : 3

第一个 "Column not found" 输出是正常的,因为无序映射中没有插入任何内容,但是,第二个不是。

我在插入的那一刻插入了一个断点并进行了调试。我观察到 *iteratorOnColumns 不是 nullptr,它指向预期的 set&lt;int&gt; 代表 column1。

肯定是插入有问题……

【问题讨论】:

  • 另外,为什么这么多指针? vector&lt;set&lt;int&gt;&gt; matrix; 不会做得很好,并大大简化代码吗?
  • 完全!我最初选择了它,但改变它认为它可能是问题的根源......

标签: c++ unordered-map nullptr


【解决方案1】:

如果我理解正确:

问题来自这样一个事实,当我尝试在 unordered_map highestMapToColumns 中找到一个列时,使用给定的键 highestIndex,它会插入对 (highestIndex,nullptr),这会阻止进一步插入相同的键在地图中...

因此highestMapToColumns,将只返回nullptr,这是使用键highestIndex插入的第一个值。

【讨论】:

  • 使用find 成员方法来检查关联容器是否包含元素,而不是自动插入它。 if(set.find(elem) != set.end()) ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-13
  • 2019-10-12
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多