52STL_set&multiset
基本概念示例代码
基本概念
set&multiset(集与多集) 用来保存大量数据
set——数据不能重复、multiset——数据可以重复
set结构速度较vector结构更快(其使用了二叉树结构)
基本操作
insert() 插入后会自动排序count() 和find() count用来统计数据出现的个数,find用来查找数据,但是不能通过find对数据进行修改!erase() 用来删除数据
示例代码
#include <iostream>
#include <set>
using namespace std
;
template
<typename Container
>
void PrintContents(const Container
&c
);
typedef set
<int> SETINT
;
typedef multiset
<int> MSETINT
;
int main()
{
set
<int> a
;
multiset
<int> ma
;
a
.insert(60);
a
.insert(-1);
a
.insert(3000);
a
.insert(60);
PrintContents(a
);
ma
.insert(3000);
ma
.insert(a
.begin(), a
.end());
ma
.insert(3000);
ma
.count(3000);
cout
<< "multiset里有" << ma
.count(3000) << "个3000" << endl
;
PrintContents(ma
);
SETINT b
;
b
.insert(43);
b
.insert(78);
b
.insert(-1);
b
.insert(124);
SETINT
::const_iterator j
;
for(j
= b
.begin(); j
!= b
.end(); ++j
)
cout
<< *j
<< endl
;
SETINT
::iterator j_found
= a
.find(-1);
if(j_found
!= b
.end())
cout
<< "找到了:" << *j_found
<< endl
;
else
cout
<< "没找到" << endl
;
cout
<< endl
;
MSETINT c
;
c
.insert(43);
c
.insert(78);
c
.insert(78);
c
.insert(124);
c
.insert(-1);
MSETINT
::const_iterator k
;
cout
<< "multiset里有" << c
.size() << "个数据." << endl
;
PrintContents(c
);
cout
<< "要删除的数据:";
int nNumberToErase
= 0;
cin
>> nNumberToErase
;
c
.erase(nNumberToErase
);
cout
<< "删除后的数据是:" << endl
;
PrintContents(c
);
c
.clear();
PrintContents(c
);
return 0;
}
template
<typename Container
>
void PrintContents(const Container
&c
)
{
typename Container
::const_iterator i
= c
.begin();
while(i
!= c
.end())
{
cout
<< *i
<< endl
;
++i
;
}
cout
<< endl
;
}