erase函数
语法:erase
1 2 3 |
void erase(iterator __position); size_type erase(const key_type& __x); void erase(iterator __first, iterator __last); |
erase()删除集合中的元素
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
/** * @brief Erases an element from a %set. * @param position An iterator pointing to the element to be erased. * * This function erases an element, pointed to by the given iterator, * from a %set. Note that this function only erases the element, and * that if the element is itself a pointer, the pointed-to memory is not * touched in any way. Managing the pointer is the user's responsibilty. */ void erase(iterator __position) { typedef typename _Rep_type::iterator _Rep_iterator; _M_t.erase((_Rep_iterator&)__position); } /** * @brief Erases elements according to the provided key. * @param x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * a %set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibilty. */ size_type erase(const key_type& __x) { return _M_t.erase(__x); } /** * @brief Erases a [first,last) range of elements from a %set. * @param first Iterator pointing to the start of the range to be * erased. * @param last Iterator pointing to the end of the range to be erased. * * This function erases a sequence of elements from a %set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibilty. */ void erase(iterator __first, iterator __last) { typedef typename _Rep_type::iterator _Rep_iterator; _M_t.erase((_Rep_iterator&)__first, (_Rep_iterator&)__last); } |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <set> using namespace std; int main() { set<int> s1; s1.insert(10); s1.insert(12); s1.insert(13); s1.insert(9); cout<<"s1集合中元素:"<<endl; set<int>::iterator iter = s1.begin(); for(;iter!=s1.end();iter++){ cout<<*iter<<" "; } cout<<endl; //size_type erase(const key_type& __x); s1.erase(9); cout<<"s1集合去除9元素:"<<endl; iter = s1.begin(); for(;iter!=s1.end();iter++){ cout<<*iter<<" "; } cout<<endl; //void erase(iterator __position); s1.erase(s1.begin()); cout<<"s1集合去除第一位元素:"<<endl; iter = s1.begin(); for(;iter!=s1.end();iter++){ cout<<*iter<<" "; } cout<<endl; //void erase(iterator __first, iterator __last); s1.erase(s1.begin(),s1.end()); cout<<"s1集合中元素个数:"<<s1.size()<<endl; } |
测试结果:
1 2 3 4 5 6 7 |
s1集合中元素: 9 10 12 13 s1集合去除9元素: 10 12 13 s1集合去除第一位元素: 12 13 s1集合中元素个数:0 |