面临删除集合中最后一个元素的问题:
#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;
}
遇到运行时问题,也尝试过使用auto、Iterator 和Const iterator,但没有用.有没有其他方法可以从集合中删除一个元素?
编辑:如何根据迭代器引用删除特定元素? 如果我喜欢:
自动 it=a.begin();
a.删除(它);这里它 = 对要删除的元素的引用
它不起作用。是否有其他基于迭代器引用的删除方法?
最佳答案
Is there any other way to erase an element from a set ?
a.erase(std::prev(std::end(a)));
Can you tell me,whats problem with my code ?
itr.base()
其中 itr == a.begin()
等同于 a.end()
。请参阅:http://en.cppreference.com/w/cpp/iterator/reverse_iterator/base
删除尾后迭代器是未定义的行为。
关于c++ - 如何使用反向迭代器从 `std::set` 删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47238865/