set::emplace()函数是预定义的函数,如果element是唯一的,则用于将新元素插入集合。
原型:
set<T> st; //声明 st.emplace(T item);
参数: T项;// T是数据类型
返回类型:如果成功插入,则返回对<迭代器指针,指向插入的值True>,否则返回对<迭代器,指向集合中的现有值,False>
用法:该函数在集合中插入唯一元素。
示例
For a set of integer, set<int> st; st.emplace(5); st.emplace(4); set content: //始终排序(有序) 4 5 st.emplace(5) //这次没有插入 set content: 4 5
包含的头文件:
#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";
if(st.empty()){
cout<<"empty set\n";
return;
}
for(it=st.begin();it!=st.end();it++)
cout<<*it<<" ";
cout<<endl;
}
int main(){
cout<<"Example of emplace function\n";
set<int> st;
set<int>:: iterator it;
cout<<"inserting 4\n";
st.emplace(4);
cout<<"inserting 6\n";
st.emplace(6);
cout<<"inserting 10\n";
st.emplace(10);
printSet(st); //打印当前设置
return 0;
}输出结果
Example of emplace function inserting 4 inserting 6 inserting 10 Set contents are: 4 6 10