set::erase()函数是预定义的函数,用于删除集合中的元素。
原型:
set<T> st; //声明 set<T>::iterator it; //迭代器声明 st.erase( const T item); //原型1- or st.erase(iterator position) //原型2-
参数:
const T item; //原型1- Or Iterator position //原型2-
返回类型:
size_type //原型1- Or void //原型2-
用法:该函数用于根据元素的值或元素在集合中的迭代器位置来擦除它
示例
For a set of integer, set<int> st; set<int>::iterator it; st.insert(4); st.insert(5); set content: 4 5 st.erase(4); set content: 5 st.erase(st.begin()); //擦除5- set content: empty set
包含的头文件:
#include <iostream> #include <set> OR #include <bits/stdc++.h>
C ++实现:
#include <bits/stdc++.h> using namespace std; void printSet(set<int> st){ set<int>:: iterator it; cout<<"Set contents are:\n"; for(it=st.begin();it!=st.end();it++) cout<<*it<<" "; cout<<endl; } int main(){ cout<<"Example of erase function\n"; set<int> st; set<int>:: iterator it; cout<<"inserting 4\n"; st.insert(4); cout<<"inserting 6\n"; st.insert(6); cout<<"inserting 10\n"; st.insert(10); printSet(st); //打印当前设置 cout<<"erasing 6..\n"; st.erase(6); //原型1- cout<<"After erasing 6...\n"; printSet(st); cout<<"erasing first element of the set now\n"; st.erase(st.begin());//原型2- cout<<"after erasing first element of set now\n"; printSet(st); return 0; }
输出结果
Example of erase function inserting 4 inserting 6 inserting 10 Set contents are: 4 6 10 erasing 6.. After erasing 6... Set contents are: 4 10 erasing first element of the set now after erasing first element of set now Set contents are: 10