下面的代碼會經歷循環太多次,而我爲什麼會感到困惑。我環顧四周,並沒有看到像這樣的案例。我對迭代器相當陌生,所以這裏可能有些簡單。感謝您的幫助!希望對未來的其他人有所幫助。迭代器,導致seg錯誤的循環!爲什麼它循環太多?
std::multimap<std::string,std::vector<Token> >::iterator end = theFacts.returnContents().end();
for (mapITER = theFacts.returnContents().begin() ; mapITER != end; mapITER++) {
cout << "ANOTHER ITERATION THROUGH FACTS" << endl;
cout << mapITER->first << endl;
cout << contents.begin()->first << endl;
if (mapITER->first == contents.begin()->first) {
cout << "same scheem type so I keep going!" << endl;
bool successfull = true;
cout << "starting to seek match --> size --> " << mapITER->second.size() << endl;
for (int x = 0; x< mapITER->second.size(); x++) {
std::cout << "processing! "
<< mapITER->second[x].getTokensValue() << "<<<<<<is equal?>>>>>>"
<< contents.begin()->second[x].getTokensValue() << std::endl;
if (mapITER->second[x].getTokensValue()
== contents.begin()->second[x].getTokensValue()) {
cout << "pushing value" << endl;
newBaby.push_back(contents.begin()->second[x]);
} else {
cout << "failure" << endl;
successfull = false;
}
}
if (successfull) {
std::cout << "match successfully found" << std::endl;
if (returnme.contents.empty()) {
returnme = Relation(contents.begin()->first, newBaby);
cout << returnme.toString() << endl;
} else {
returnme.relationInsert(contents.begin()->first, newBaby);
cout << returnme.toString() << endl;
}
} else {
// Anser is NO
}
}
}
我知道我不能提供完整的代碼,但你可以看到形成了下面的輸出,我通過遍歷地圖的大小爲2,那麼爲什麼它循環第三次!
WHERE TO END --> size of maps (number of iterations that shoudl occure2
ANOTHER ITERATION THROUGH FACTS
snap
snap
same scheem type so I keep going!
starting to seek match --> size --> 4
processing! '12345'<<<<<<is equal?>>>>>>'67890'
failure
processing! 'Snoopy'<<<<<<is equal?>>>>>>'Van Pelt'
failure
processing! '12 Apple'<<<<<<is equal?>>>>>>'34 Pear'
failure
processing! '555-1234'<<<<<<is equal?>>>>>>'555-5678'
failure
ANOTHER ITERATION THROUGH FACTS
snap
snap
same scheem type so I keep going!
starting to seek match --> size --> 4
processing! '67890'<<<<<<is equal?>>>>>>'67890'
pushing value
processing! 'Van Pelt'<<<<<<is equal?>>>>>>'Van Pelt'
pushing value
processing! '34 Pear'<<<<<<is equal?>>>>>>'34 Pear'
pushing value
processing! '555-5678'<<<<<<is equal?>>>>>>'555-5678'
pushing value
match successfully found
PRINT RELATION CALLED
snap('67890','Van Pelt','34 Pear','555-5678')
ANOTHER ITERATION THROUGH FACTS
Segmentation fault (core dumped)
這裏是返回內容的作用。
std::multimap<std::string,std::vector<Token> > Relation :: returnContents()
{
return contents;
}
其中內容是Relation類中的私有變量。在我看來,這不應該導致錯誤,除非有什麼明顯的我不知道。
這將幫助,如果你表現出了足夠的代碼來診斷問題,像在哪裏'end'聲明和它的價值是什麼? –
'mapITER!= end'中的'end'是什麼? –
在您的情況下嘗試使用mapITER!= theFacts.end()。並且迭代器的前增量更好(不要複製對象) –