Fehler MCS VS - empty Vector
-
Hallo zusammen,
lerne gerade C++ - leider tritt bei meinem Code der folgende Fehler auf.
Kann mir bitte jemand sagen, wie ich das Problem löse ?
Debug Assertion Failed!
Program:
...atri\source\repos\HalloWeltproject\Debug\HalloWeltproject.exe
File: c\program files (x86)\microsoft visual
studio\2017\community\vc\tools\msvc\14.16.27023\include\vector
Line: 1780
Expression: front() called on emtpy vector
Gruß
Patrick
-
Etwas in den vector reinstecken bevor du etwas rausholst?
-
Hallo,
danke für das rasche Feedback.
Sorry vorab für die Folgefrage - aber ich habe in meinem Code keinen Vector - siehe wie folgt:
int main(int argc, const char * argv[]) {
ifstream fin("C:\\Users\\patri\\Downloads\\faust.txt"); map<string, int> occurrences; while (!fin.eof()) { string word; fin >> word; if (occurrences.count(word) == 0) { occurrences.insert(pair<string, int>(word, 1)); } else { occurrences[word]++; } } cout << occurrences.size() << endl; priority_queue<pair<int, string>> pq; for (const auto &entry : occurrences) { pair<int, string> pqEntry(entry.second, entry.first); pq.push(pqEntry); } for (int i = 0; i < 20; i++) { cout << pq.top().second << ": " << pq.top().first << endl; pq.pop(); } fin.close();
}
-
Eine priority_queue wird mit einem vector implementiert. Da du ohne Rücksicht auf Verluste top/pop aufrufst, ist der vector irgendwann leer. Der Debugger sagt dir wann.
-
@NicerDicerplus sagte in Fehler MCS VS - empty Vector:
for (int i = 0; i < 20; i++)
Anstelle dieser Schleife könntest du sowas machen wie
while (!pq.empty())
oder wenn du bei deinem for bleiben willst, machst du den Check auf empty eben in der Loop, z.B. so:for (int i = 0; i < 20; i++) { if (pq.empty()) { cout << "Keine weiteren Elemente in der Queue\n"; break; } cout << pq.top().second << ": " << pq.top().first << endl; pq.pop(); }
-
besten Dank an alle für den klasse Support.