//构造函数
//set()
set<int> s1;
//指定一个比较函数来创建set对象
struct KeyCompare
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
set<const char*, KeyCompare> s2;
//set(const _Myt& _Right)
set<int> s3(s1);
//set(_Iter _First, _Iter _Last)
int arr[] = { 1, 33, 12, 4, 9 };
set<int> s4(arr, arr + 5);
const char* szArray[] = { "hfdd", "do", "mmd" };
set<const char*, KeyCompare> s5(szArray, szArray + 3, KeyCompare()); //do hfdd mmd
//插入元素
pair<set<int>::iterator, bool> nRet = s1.insert(3);
if (nRet.second)
{
cout << "insert success" << endl;
}
s1.insert(4);
s1.insert(12);
//在可能的位置之前插入元素
set<int>::iterator i = s1.insert(s1.begin(), 7);
set<int>::iterator iter;
for (iter = s1.begin(); iter != s1.end(); ++iter)
{
cout << *iter << endl; //3 4 7 12
}
cout << endl;
//插入区间元素
s1.insert(s4.begin(), s4.end());
for (iter = s1.begin(); iter != s1.end(); ++iter)
{
cout << *iter << endl; //1 3 4 7 9 12 33
}
cout << endl;
set<int>::reverse_iterator rIter;
for (rIter = s1.rbegin(); rIter != s1.rend(); ++rIter)
{
cout << *rIter << endl; //33 12 9 7 4 3 1
}
cout << endl;
set<int>::iterator rFind = s1.find(7);
if (rFind == s1.end())
{
cout << "not find" << endl;
}
else
{
int i = 0;
iter = s1.begin();
while (iter != rFind)
{
++i;
++iter;
}
cout << "find index:" << i << endl;
}
//删除元素
s1.erase(s1.begin()); //3 4 7 9 12 33
//删除键值33的元素
s1.erase(33); //3 4 7 9 12
//删除区间元素
s1.erase(s1.begin(), ++s1.begin()); //4 7 9 12
//删除所有元素
s1.clear();
//容器是否为空
bool b = s1.empty();
//实际元素个数
size_t count = s1.size();