这篇学习set容器的大小操作,大小主要有判断是否为空,size()还有交换swap(),最后来学习下set容器的插入和删除操作。基本上那些常用的API,前面都学习过。
1.set容器大小操作和交换
函数原型
注意这里set容器没有resize(),重新指定容器大小的操作。
#include <iostream>
#include <string>
#include <set>
using namespace std;
void printSet(const set<int>& st)
{
for(set<int>::const_iterator it = st.begin(); it != st.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void test01()
{
// set的大小操作
set<int> st;
// 插入元素
st.insert(20);
st.insert(30);
st.insert(10);
st.insert(50);
st.insert(50);
printSet(st);
// 判断是否为空
cout << "is Empty?" << st.empty() << endl;
// 返回set容器的大小
cout << "size: " << st.size() << endl;
// 容器交换
set<int> st1;
// 插入元素
st1.insert(200);
st1.insert(300);
cout << "before swap " << endl;
printSet(st);
printSet(st1);
cout << "after swap " << endl;
st1.swap(st);
printSet(st);
printSet(st1);
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果
2.set容器的插入操作
set容器插入比较特殊,没有前面提供哪些push_back,只有一个insert(ele),而且不能指定插入位置,参数就是一个元素,由于set容器会自动排序,所以插入的api就一个insert(ele),这个插入的方法,上面代码也使用到了,就不再练习。
直接来看删除相关
函数原型
接下来用代码来练习一下几个删除的方法
#include <iostream>
#include <string>
#include <set>
using namespace std;
void printSet(const set<int>& st)
{
for(set<int>::const_iterator it = st.begin(); it != st.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void test01()
{
// set的大小操作
set<int> st;
// 插入元素
st.insert(20);
st.insert(30);
st.insert(10);
st.insert(50);
printSet(st);
// 根据迭代器位置删除元素
st.erase(st.begin());
printSet(st);
// 根据元素删除
st.erase(50);
printSet(st);
// 清空容器
st.clear();
cout << "is Empty? " << st.empty() << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果
3.set容器的查找和统计
查找元素是否存在和统计元素的个数
函数原型
注意,find()函数的返回值是一个迭代器,也就是调用这个函数,是通过迭代器一个一个去帮你查找,如果查找到就返回迭代器的位置,如果找不到就返回迭代器最后查找的位置,也就是迭代器查找到最后还是没有找到元素。统计函数count()的结果无非就是0和1
测试代码
#include <iostream>
#include <string>
#include <set>
using namespace std;
void printSet(const set<int>& st)
{
for(set<int>::const_iterator it = st.begin(); it != st.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void test01()
{
// set的大小操作
set<int> st;
// 插入元素
st.insert(20);
st.insert(30);
st.insert(10);
st.insert(50);
printSet(st);
// 查找元素
set<int>::iterator pos = st.find(30);
if(pos != st.end())
{
cout << "had find " << endl;
}
else
{
cout << "not find " << endl;
}
// 统计
int cot = st.count(30);
cout << "the count of element 30 is " << cot << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果