Sets/Multisets:内部的元素依据其值自动排序,Set内的相同数值的元素只能出现一次,Multisets内可包含多个数值相同的元素,内部由二叉树实现(实际上基于红黑树(RB-tree)实现),便于查找; map和multisets也一样
1.构造
#include <iostream>
#include <set>
bool fncomp (
int lhs,
int rhs) {
return lhs<rhs;}
struct classcomp {
bool operator() (
const int& lhs,
const int& rhs)
const
{
return lhs<rhs;}
};
int main ()
{
std::
set<int> first;
int myints[]= {
10,
20,
30,
40,
50};
std::
set<int> second (myints,myints+
5);
std::
set<int> third (second);
std::
set<int> fourth (second.begin(), second.end());
std::
set<int,classcomp> fifth;
bool(*fn_pt)(
int,
int) = fncomp;
std::
set<int,bool(*)(int,int)> sixth (fn_pt);
return 0;
}
2.操作
2.1容量大小
2.2modify access
#include <iostream>
#include <set>
#include<QDebug>
int main ()
{
std::
set<int> myset;
for (
int i=
1; i<=
5; ++i) myset.insert(i*
10);
int myints[]= {
5,
10,
15};
myset.insert (myints,myints+
3);
myset.insert(
11);
myset.erase(myset.cbegin());
auto it=myset.find(
15);
myset.erase(myset.begin(),it);
myset.erase(
20);
myset.clear();
return 0;
}
2.3其他
#include <iostream>
#include <set>
int main ()
{
std::
set<int> myset;
std::
set<int>::iterator it;
for (
int i=
1; i<=
5; i++) myset.insert(i*
10);
it=myset.find(
20);
myset.erase (it);
myset.erase (myset.find(
40));
std::
cout <<
"myset contains:";
for (it=myset.begin(); it!=myset.end(); ++it)
std::
cout <<
' ' << *it;
std::
cout <<
'\n';
return 0;
}
#include <iostream>
#include <set>
int main ()
{
std::
set<int> myset;
for (
int i=
1; i<
5; ++i) myset.insert(i*
3);
for (
int i=
0; i<
10; ++i)
{
std::
cout << i;
if (myset.count(i)!=
0)
std::
cout <<
" is an element of myset.\n";
else
std::
cout <<
" is not an element of myset.\n";
}
return 0;
}
#include <iostream>
#include <set>
int main ()
{
std::
set<int> myset;
std::
set<int>::iterator itlow,itup;
for (
int i=
1; i<
10; i++) myset.insert(i*
10);
itlow=myset.lower_bound (
30);
itup=myset.upper_bound (
60);
myset.erase(itlow,itup);
std::
cout <<
"myset contains:";
for (
std::
set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
std::
cout <<
' ' << *it;
std::
cout <<
'\n';
return 0;
}