マルチセットコンテナのイテレータのセットを別のデータ構造で維持しています。しばらくして、このデータ構造から1つのイテレーターを選択し、マルチセットからそのイテレーターに関連付けられた要素を消去します。私はこれを最初にこのようなものを使用します:
#include <iostream>
#include <set>
int main ()
{
std::multiset<int> myints;
std::cout << "0. size: " << myints.size() << '\n';
for (int i=0; i<10; i++) myints.insert(i);
std::cout << "1. size: " << myints.size() << '\n';
myints.insert (5);
std::cout << "2. size: " << myints.size() << '\n';
std::multiset<int>::iterator it = myints.find(5);
myints.erase (it);
std::cout << "3. size: " << myints.size() << '\n';
myints.erase (it);
std::cout << "4. size: " << myints.size() << '\n';
return 0;
}
ただし、2番目のmyints.erase (it);
原因はセグメンテーション違反です。したがって、次のコードに変更して動作します。これが良い方法なのか、それとも実行可能なundefined
状況なのか疑問に思いました。
int main ()
{
std::multiset<int> myints;
std::cout << "0. size: " << myints.size() << '\n';
for (int i=0; i<10; i++) myints.insert(i);
std::cout << "1. size: " << myints.size() << '\n';
myints.insert (5);
std::cout << "2. size: " << myints.size() << '\n';
std::multiset<int>::iterator it = myints.find(5);
myints.erase (it);
std::cout << "3. size: " << myints.size() << '\n';
std::multiset<int>::iterator newit = myints.find(*it);
myints.erase (newit);
std::cout << "4. size: " << myints.size() << '\n';
return 0;
}