【问题标题】:How to erase element with a reverse iterator from a `std::set`?如何从`std::set`中使用反向迭代器擦除元素?
【发布时间】:2017-11-11 14:17:47
【问题描述】:

面临删除集合中最后一个元素的问题:

#include <bits/stdc++.h>
using namespace std;
int main()
{
set < pair <int,int > > a;
a.insert(make_pair(2,3)); 
auto it = a.rbegin();
a.erase(it.base()); // for deleting last element in set
cout << a.size() << endl;
return 0; 
}

遇到 runtime 问题,也尝试过 autoIteratorConst iterator,但无法正常工作.有没有其他方法可以从集合中删除一个元素?

编辑:如何根据迭代器引用删除特定元素? 如果我喜欢:

auto it=a.begin(); a.erase(it); Here it = reference to the element for deletion

它不起作用。基于迭代器引用的任何其他删除方式?

【问题讨论】:

标签: c++ stl c++14


【解决方案1】:

还有其他方法可以从集合中删除元素吗?

a.erase(std::prev(std::end(a)));

你能告诉我,我的代码有什么问题吗?

itr.base() 其中itr == a.begin() 等价于a.end()。见:http://en.cppreference.com/w/cpp/iterator/reverse_iterator/base

删除过去的迭代器是未定义的行为

【讨论】:

  • 谢谢,但你能告诉我,我的代码有什么问题吗?
  • 我告诉过你 - 你的.base() 调用基本上返回a.end()。然后,您将擦除一个过去的迭代器,这是未定义的行为。
  • 好的,我知道了,但是如果我直接通过,“a.erase(it)”也不起作用?即使我正在传递需要删除的元素的引用。
猜你喜欢
  • 2011-03-22
  • 2011-02-21
  • 1970-01-01
  • 2014-01-04
  • 2023-03-26
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
相关资源
最近更新 更多