2017-02-14 193 views
1

注意:我花了很多時間試圖瞭解我的問題來自哪裏。然而,當我寫這篇文章時,我發現瞭解決我的問題的辦法。然而,我認爲它仍然值得發佈。另外,我對我的解釋並不是100%肯定的。unordered_map插入失敗


這是我簡單的問題,一個簡單的例子。

matrix二元矩陣的稀疏表示。在這個例子中我選擇:

每一列由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 

第一「列未找到」輸出是正常的,因爲沒有什麼是在無序地圖插入,然而,第二個不是。

我在插入時插入了一個斷點並進行了調試。我觀察到*iteratorOnColumns不是nullptr,它指向代表column1的預期set<int>

必須有插入的一個問題...

+0

另外,爲什麼這麼多的指針?不會'矢量>矩陣;'做得很好,並簡化了很多代碼? –

+0

完全!我原來選擇了它,但改變了它認爲它可能是問題的根源...... – Prime360

回答

0

如果我理解正確:

的問題來自於事實,當我試圖找到在unordered_map highestMapToColumns一列,用給定的密​​鑰highestIndex,它插入所述一對(highestIndex,nullptr),並且這防止了在地圖中的相同的密鑰的任何進一步插入...

因此highestMapToColumns,將只返回nullptr這是用密鑰highestIndex插入的第一個值。

+1

使用'find'成員方法來檢查一個關聯容器是否包含一個元素,而不是自動插入它。 'if(set.find(elem)!= set.end())...' –