멀티 샘플에 항목을 삽입하는 샘플 코드가 있습니다. 지정된 키의 특정 항목을 삭제하려고합니다. 그러나이 코드는 무한 루프로 진행됩니다. 누군가이 코드를 도와 줄 수 있습니까?C++ STL 멀티 맵에서 특정 키의 항목 제거
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
multimap<string, string> names;
string n;
names.insert(pair<string, string>("Z", "F"));
names.insert(pair<string, string>("Z", "A"));
names.insert(pair<string, string>("S", "T"));
names.insert(pair<string, string>("S", "A"));
names.insert(pair<string, string>("S", "J"));
names.insert(pair<string, string>("D", "H"));
names.insert(pair<string, string>("D", "W"));
names.insert(pair<string, string>("D", "R"));
multimap<string, string>::iterator p;
p = names.find("Z");
if(p != names.end()) { // found a name
do {
cout << n << ", " << p->second;
cout << endl;
if (p->second.compare("A") == 0) {
names.erase(p);
p++;
} else {
p++;
}
} while (p != names.upper_bound("Z"));
}
else{
cout << "Name not found.\n";
}
p = names.find("Z");
if(p != names.end()) { // found a name
do {
cout << n << ", " << p->second;
cout << endl;
} while (p != names.upper_bound("Z"));
}
else{
cout << "Name not found.\n";
}
return 0;
}
위의 경우 키 값 "Z"를 사용하여 "A"를 삭제하려고합니다.
multimap::erase
@brown 어떻게이 문제를 해결할 수 있습니까? iterator를 임시로 복사하고 해당 임시 반복기를 사용하여 지우려고했으나 작동하지 않았습니다. – Santhosh
@ skokal01이 예제 수정으로 업데이트되었습니다. –