我在单独的数据结构中维护一组多集容器的迭代器。过了一会儿,我从这个数据结构中选择了一个迭代器,然后从多重集中删除了与该迭代器相关的元素。我首先使用这样的东西:
#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;
}
然而,事实证明第二个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;
}