c++ STL set和multiset的使用(轉)

 
c++ STL set和multiset的使用
2010-01-25 11:53
C++ STL set和multiset的使用
1,set的含義是集合,它是一個有序的容器,裏面的元素都是排序好的,支持插入,刪除,查找等操作,就 像一個集合一樣。所有的操作的都是嚴格在logn時間之內完成,效率非常高。 set和multiset的區別是:set插入的元素不能相同,但是multiset可以相同。
創建 multiset<ss> base;
刪除:如果刪除元素a,那麼在定義的比較關係下和a相等的所有元素都會被刪除
base.count( a ):set能返回0或者1,multiset是有多少個返回多少個.
Set和multiset都是引用<set>頭文件,複雜度都是logn
2,Set中的元素可以是任意類型的,但是由於需要排序,所以元素必須有一個序,即大小的比較關係,比如 整數可以用<比較.
3,自定義比較函數;
include<set>
typedef struct
{ 定義類型 }
ss(類型名);
struct cmp
{
bool operator()( const int &a, const int &b ) const
{ 定義比較關係<}
};
(運算符重載,重載<)
set<ss> base; ( 創建一個元素類型是ss,名字是base的set )
注:定義了<,==和>以及>=,<=就都確定了,STL的比較關係都是用<來確定的,所以必須通 過定義< --“嚴格弱小於”來確定比較關
4,set的基本操作:
begin() 返回指向第一個元素的迭代器
clear() 清除所有元素
count() 返回某個值元素的個數
empty() 如果集合爲空,返回true
end() 返回指向最後一個元素的迭代器
equal_range() 返回集合中與給定值相等的上下限的兩個迭代器
erase() 刪除集合中的元素
find() 返回一個指向被查找到元素的迭代器
get_allocator() 返回集合的分配器
insert() 在集合中插入元素
lower_bound() 返回指向大於(或等於)某值的第一個元素的迭代器
key_comp() 返回一個用於元素間值比較的函數
max_size() 返回集合能容納的元素的最大限值
rbegin() 返回指向集合中最後一個元素的反向迭代器
rend() 返回指向集合中第一個元素的反向迭代器
size() 集合中元素的數目
swap() 交換兩個集合變量
upper_bound() 返回大於某個值元素的迭代器
value_comp() 返回一個用於比較元素間的值的函數
5,自定義比較函數:
For example:
#include<iostream>
#include<set>
using namespace std;
typedef struct {
int a,b;
char s;
}newtype;
struct compare //there is no ().
{
bool operator()(const newtype &a, const newtype &b) const
{
return a.s<b.s;
}
};//the “; ” is here;
set<newtype,compare>element;
int main()
{
newtype a,b,c,d,t;
a.a=1; a.s='b';
b.a=2; b.s='c';
c.a=4; c.s='d';
d.a=3; d.s='a';
element.insert(a);
element.insert(b);
element.insert(c);
element.insert(d);
set<newtype,compare>::iterator it;
for(it=element.begin(); it!=element.end();it++)
cout<<(*it).a<<" ";
cout<<endl;
for(it=element.begin(); it!=element.end();it++)
cout<<(*it).s<<" ";
}
element自動排序是按照char s的大小排序的;
6.其他的set構造方法;
#include <iostream>
#include <set>
using namespace std;
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 ()
{
set<int> first; // empty set of ints
int myints[]= {10,20,30,40,50};
set<int> second (myints,myints+5); // pointers used as iterators
set<int> third (second); // a copy of second
set<int> fourth (second.begin(), second.end()); // iterator ctor.
set<int,classcomp> fifth; // class as Compare
bool(*fn_pt)(int,int) = fncomp;
set<int,bool(*)(int,int)> sixth (fn_pt); // function pointer as Compare
return 0;
}
 
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章