【发布时间】:2017-02-14 14:37:52
【问题描述】:
注意:我花了很多时间试图了解我的问题出在哪里。但是,当我写这篇文章时,我找到了解决问题的方法。然而,我认为它仍然值得发布。此外,我不能 100% 确定我的解释。
这是我的一个简单示例的简化问题。
matrix 是 二元矩阵 的稀疏表示。在这个例子中我选择了:
1 0
1 1
0 0
1 1
每一列都由set<int> 表示,给出非零元素的索引。例如,对于矩阵的第一列,索引 {0,1,3} 的行不为零。
算法目标:
- 对于每一列,找到该列的最高索引(例如,第一列是 3),查看
highestMapToColumnsunordered_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<int> 代表 column1。
肯定是插入有问题……
【问题讨论】:
-
另外,为什么这么多指针?
vector<set<int>> matrix;不会做得很好,并大大简化代码吗? -
完全!我最初选择了它,但改变它认为它可能是问题的根源......
标签: c++ unordered-map nullptr