c++ - 使用迭代器从 STL 多重集中删除元素

标签 c++ data-structures stl multiset

我在单独的数据结构中维护一组多重集容器的迭代器。过了一会儿,我从这个数据结构中选择了一个迭代器,然后从多重集中删除了与该迭代器相关的元素。我首先使用这样的东西:

#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;
}

最佳答案

erase(it) 使迭代器 it 无效,即它在 erase 之后无用,对它做任何事情都会导致未定义的行为。 (你可能期望它在它指向的元素被删除时“移动到下一个元素”,但事实并非如此。)

您的第二种方法无法解决此问题。它可能偶然起作用,但在删除它之后您仍在重复使用


编辑:鉴于您的描述“我只想从多重集中删除一个 5 并在删除后为下一次删除保持有效。”,您可以通过创建迭代器的拷贝来做到这一点,递增原件然后删除拷贝:

it = myints.find(5);
// better add a check here to make sure there actually is a 5 ...
std::multiset<int>::iterator newit = it;
it++;
myints.erase(newit);

因为您已经递增了,所以它仍然有效,因为它没有指向被erase杀死的元素。

但是,老实说,我无法想象这可能真的有用,或者更确切地说,需要的情况。

关于c++ - 使用迭代器从 STL 多重集中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14846296/

相关文章:

java - 我的 DFS 图形方法不会从 int 变为 String

c++ - 检查某个位置的元素是否存在(设置)在 STL vector 中

c++ - 为什么 C++ STL 使用 RBtree 来实现 "std::map"?

Delphi XE7 的 C++ 函数

c++ - valarray 就地操作给出与临时赋值不同的结果

algorithm - 线段树第 K 个最大值

c++ - 静态或堆栈分配数组的可变大小元素是否驻留在堆空间中?

c++ - STL中的容量和复制

c++ - C++中的新行错误

c++ - 保留 vector 是线程安全的吗?