2012-04-09 68 views
1

我試圖插入一個地圖的內容到另一個。下面是代碼:爲什麼在插入地圖時遇到seg錯誤?

std::map<std::string, int> Student::getGrades() const; 
... 

for(set<Student*, Cmp>::const_iterator it = s.begin(); it!=s.end(); ++it) 
{ 
    grades.clear(); 
    grades.insert((*it)->getGrades().begin(), (*it)->getGrades().end()); 
    for(map<string, int>::const_iterator itt = grades.begin(); itt!=grades.end(); ++itt) 
    { 
     if(itt->first == course && itt->second >= score1 && itt->second <= score2) 
      (*it)->display(cout); 
    } 
} 

s是一組包含指向學生對象和每個學生對象具有getGrades()方法返回的地圖。我試圖找到與我從文件中讀入的成績相匹配的成績,並打印與這些成績對應的記錄。但是,插入方法給了我一個seg故障。有什麼建議麼?

+2

你可以顯示'Student :: getGrades()'的聲明嗎? – alexisdm 2012-04-09 03:16:43

回答

3

如果getGrades()返回等級圖的副本而不是參考,begin()end()將屬於2個不同的地圖。

你或許應該做一個本地副本,並簡化了這樣的代碼:

for(set<Student*, Cmp>::const_iterator it = s.begin(); it!=s.end(); ++it) 
{ 
    map<string, int> grades = (*it)->getGrades(); 
    for(map<string, int>::const_iterator itt = grades.begin(); itt!=grades.end(); ++itt) 
    { 
     if(itt->first == course && itt->second >= score1 && itt->second <= score2) 
      (*it)->display(cout); 
    } 
} 
+0

修好了!非常感謝! – Strata 2012-04-09 03:53:28

0

有可能是在集合s一個未初始化的指針。

相關問題