【问题标题】:Why std::set::erase is not consistent with std::set::insert?为什么 std::set::erase 与 std::set::insert 不一致?
【发布时间】:2018-06-22 13:17:27
【问题描述】:

为什么没有从myset 中减去第二组? myset.insert(second.begin(),second.end()) 按预期工作。

// erasing from set
int main ()
{
  std::set<int> myset;
  std::set<int> second;
  std::set<int>::iterator it;

  // insert some values:
  for (int i=1; i<10; i++) myset.insert(i*10);  // 10 20 30 40 50 60 70 80 90
  for (int i=3; i<5; i++) second.insert(i*10); 

  myset.erase(second.begin(), second.end()); // Why is the second set not subtracted from myset?  myset.insert(second.begin(),second.end()) works as intended.

  std::cout << "myset contains:";
  for (it=myset.begin(); it!=myset.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

【问题讨论】:

标签: c++ algorithm set


【解决方案1】:

std::set::erase 期望迭代器指向您调用它的集合。将 it 迭代器提供给另一组将不起作用。您想要的是std::set_difference,您将这两个集合都传递给它,它将输出一个新集合,其中包含第一个集合中的所有元素,而不是第二个集合。对你来说看起来像

std::set diff;
std::set_difference(myset.begin(), myset.end(), 
                    second.begin(), second.end(), 
                    std::inserter(diff, diff.begin()));

【讨论】:

  • 它是否比循环第二组并为每个元素调用 myset.erase(it) 更有效? myset 的大小为 100,第二组的大小为 10。
  • @AdityaBudaraju 您必须对其进行分析,但我认为性能相当。我自己也喜欢这种方法,因为它是单线。
【解决方案2】:

erase 在它正在处理的集合中获取迭代器

 Removes the elements in the range [first; last), which must be a valid range in *this.

https://en.cppreference.com/w/cpp/container/set/erase

【讨论】:

    猜你喜欢
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多