要使用set就要使用#include <set>头文件
set就是一个集合,他会自动去重,自动排序
定义set
#include <set>
#include <algorithm>
using namespace std;
int main()
{
set</*类型,比如int,结构体也可以*/typename> /*文件名*/st;
return 0;
}
插入
#include <set>
#include <algorithm>
using namespace std;
int main()
{
st.insert(x);
//x为st 的类型
return 0;
}
迭代器
#include <set>
#include <algorithm>
using namespace std;
int main()
{
set<typename>::iterator it;
return 0;
}
迭代器可以用来访问set
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
set<typename>::iterator it;
cout << *it << endl;
//*it就是set里面的元素
return 0;
}
删除set中的元素
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
set<typename>::iterator it;
st.erase(it);//it为迭代器,st.erase(it)是代表删除it位置的元素
st.erase(x);//x为具体元素,st.erase(x)表示删除x元素
st.erase(it1,it2);//it1,it2皆为迭代器,表示删除[it1,it2)区间的元素,注意是左闭右开
return 0;
}
清空set
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
st.clear();//注意不要传入任何参数,如果传入的话,会报错
//[Error] no matching function for call to 'std::set<int>::clear(int)
return 0;
}
第一个位置以及最后一个位置
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
it1 = st.begin();
it2 = st.end();//注意st.end()是最后一个位置+1
return 0;
}
访问set
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
set<typename>::iterator it;
for (it = st.begin();it != st.end();it++)
{
//注意判断条件不是 it < st.end();
//而是 it != st.end();
}
return 0;
}
lower_bound以及upper_bound
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
it = st.lower_bound(x);//在st里找到第一个大于等于x的位置,返回迭代器
it = st.upper_bound(x);//在st里找到第一个严格大于x的位置,返回迭代器
//如果用set自带的lower_bound或upper_bound,时间复杂度是O(logn)
//但使用algorithm里的lower_bound或upper_bound,时间复杂度是O(n)
return 0;
}
multiset是多重集合,一个数可以出现多遍,但使用erase时,会有一些变化
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
multiset<typename> st;
st.erase(x);//x为具体元素,如果有多个x,会把所有的x都删除
//但如果是迭代器,只会删除it位置的元素
return 0;
}