C++ STL set惯用函数大全

C++ STL set常用函数大全

c++ stl集合set介绍 c++ stl集合(Set)是一种包含已排序对象的关联容器。set/multiset会根据待定的排序准则,自动将元素排序。两者不同在于前者不允许元素重复,而后者允许。1) 不能直接改变元素值,因为那样会打乱原...


c++ stl集合set介绍

   c++ stl集合(Set)是一种包含已排序对象的关联容器。set/multiset会根据待定的排序准则,自动将元素排序。两者不同在于前者不允许元素重复,而后者允许。

1) 不能直接改变元素值,因为那样会打乱原本正确的顺序,要改变元素值必须先删除旧元素,则插入新元素

2) 不提供直接存取元素的任何操作函数,只能通过迭代器进行间接存取,而且从迭代器角度来看,元素值是常数

3) 元素比较动作只能用于型别相同的容器(即元素和排序准则必须相同)

set模板原型://Key为元素(键值)类型


template <class Key, class Compare=less<Key>, class Alloc=STL_DEFAULT_ALLOCATOR(Key) >

从原型可以看出,可以看出比较函数对象及内存分配器采用的是默认参数,因此如果未指定,它们将采用系统默认方式。


set的各成员函数列表如下:

c++ stl容器set成员函数:begin()--返回指向第一个元素的迭代器

c++ stl容器set成员函数:clear()--清除所有元素

c++ stl容器set成员函数:count()--返回某个值元素的个数

c++ stl容器set成员函数:empty()--如果集合为空,返回true

c++ stl容器set成员函数:end()--返回指向最后一个元素的迭代器

c++ stl容器set成员函数:equal_range()--返回集合中与给定值相等的上下限的两个迭代器

c++ stl容器set成员函数:erase()--删除集合中的元素

c++ stl容器set成员函数:find()--返回一个指向被查找到元素的迭代器

c++ stl容器set成员函数:get_allocator()--返回集合的分配器

c++ stl容器set成员函数:insert()--在集合中插入元素

c++ stl容器set成员函数:lower_bound()--返回指向大于(或等于)某值的第一个元素的迭代器

c++ stl容器set成员函数:key_comp()--返回一个用于元素间值比较的函数

c++ stl容器set成员函数:max_size()--返回集合能容纳的元素的最大限值

c++ stl容器set成员函数:rbegin()--返回指向集合中最后一个元素的反向迭代器

c++ stl容器set成员函数:rend()--返回指向集合中第一个元素的反向迭代器

c++ stl容器set成员函数:size()--集合中元素的数目

c++ stl容器set成员函数:swap()--交换两个集合变量

c++ stl容器set成员函数:upper_bound()--返回大于某个值元素的迭代器

c++ stl容器set成员函数:value_comp()--返回一个用于比较元素间的值的函数


c++ stl集合set插入,遍历用法举例

#include<iostream> 
#include<set> 
using namespace std; 
//set插入元素操作  
int main() 
{ 
    //定义一个int型集合对象s,当前没有任何元素.由www.169it.com搜集整理
    set<int> s; 
    s.insert(8);  //第一次插入8,可以插入  
    s.insert(1); 
    s.insert(12); 
    s.insert(6); 
    s.insert(8);   //第二次插入8,重复元素,不会插入  
    set<int>::iterator it; //定义前向迭代器 
    //中序遍历集合中的所有元素  
    for(it=s.begin();it!=s.end();it++) 
    cout<<*it<<endl;    
    system("pause"); 
    return 0; 
}


更详细点的用法举例

#include <iostream>
#include <string>
#include <set>

using namespace std;

struct strLess
{
   bool operator() (const char *s1, const char *s2) const
   {
    return strcmp(s1, s2) < 0;
   }
};

void printSet(set<int> s)
{
copy(s.begin(), s.end(), ostream_iterator<int>(cout, ", ") );

// set<int>::iterator iter;
// for (iter = s.begin(); iter != s.end(); iter++)
//    //cout<<"set["<<iter-s.begin()<<"]="<<*iter<<", "; //Error
//    cout<<*iter<<", ";
cout<<endl;
}

void main()
{
//创建set对象,共5种方式,提示如果比较函数对象及内存分配器未出现,即表示采用的是系统默认方式
//创建空的set对象,元素类型为int,
set<int> s1; 
//创建空的set对象,元素类型char*,比较函数对象(即排序准则)为自定义strLess
set<const char*, strLess> s2( strLess); 
//利用set对象s1,拷贝生成set对象s2
set<int> s3(s1); 
//用迭代区间[&first, &last)所指的元素,创建一个set对象
int iArray[] = {13, 32, 19};
set<int> s4(iArray, iArray + 3);
//用迭代区间[&first, &last)所指的元素,及比较函数对象strLess,创建一个set对象
const char* szArray[] = {"hello", "dog", "bird" };
set<const char*, strLess> s5(szArray, szArray + 3, strLess() );

//元素插入:
//1,插入value,返回pair配对对象,可以根据.second判断是否插入成功。(提示:value不能与set容器内元素重复)
//pair<iterator, bool> insert(value)
//2,在pos位置之前插入value,返回新元素位置,但不一定能插入成功
//iterator insert(&pos, value)
//3,将迭代区间[&first, &last)内所有的元素,插入到set容器
//void insert[&first, &last)
cout<<"s1.insert() : "<<endl;
for (int i = 0; i <5 ; i++)
    s1.insert(i*10);
printSet(s1);

cout<<"s1.insert(20).second = "<<endl;;
if (s1.insert(20).second)
    cout<<"Insert OK!"<<endl;
else
    cout<<"Insert Failed!"<<endl;

cout<<"s1.insert(50).second = "<<endl;
if (s1.insert(50).second)
{cout<<"Insert OK!"<<endl; printSet(s1);}
else
    cout<<"Insert Failed!"<<endl;

cout<<"pair<set<int>::iterator::iterator, bool> p;\np = s1.insert(60);\nif (p.second):"<<endl;
pair<set<int>::iterator::iterator, bool> p;
p = s1.insert(60);
if (p.second)
{cout<<"Insert OK!"<<endl; printSet(s1);}
else
   cout<<"Insert Failed!"<<endl;

//元素删除
//1,size_type erase(value) 移除set容器内元素值为value的所有元素,返回移除的元素个数
//2,void erase(&pos) 移除pos位置上的元素,无返回值
//3,void erase(&first, &last) 移除迭代区间[&first, &last)内的元素,无返回值
//4,void clear(), 移除set容器内所有元素

cout<<"\ns1.erase(70) = "<<endl;
s1.erase(70);
printSet(s1);
cout<<"s1.erase(60) = "<<endl;
s1.erase(60);
printSet(s1);

cout<<"set<int>::iterator iter = s1.begin();\ns1.erase(iter) = "<<endl;
set<int>::iterator iter = s1.begin();
s1.erase(iter);
printSet(s1);

//元素查找
//count(value)返回set对象内元素值为value的元素个数
//iterator find(value)返回value所在位置,找不到value将返回end()
//lower_bound(value),upper_bound(value), equal_range(value) 略
cout<<"\ns1.count(10) = "<<s1.count(10)<<", s1.count(80) = "<<s1.count(80)<<endl;
cout<<"s1.find(10) : ";
if (s1.find(10) != s1.end()) 
    cout<<"OK!"<<endl;
else
    cout<<"not found!"<<endl;

cout<<"s1.find(80) : ";
if (s1.find(80) != s1.end()) 
    cout<<"OK!"<<endl;
else
    cout<<"not found!"<<endl;

//其它常用函数
cout<<"\ns1.empty()="<<s1.empty()<<", s1.size()="<<s1.size()<<endl;
set<int> s9;
s9.insert(100);
cout<<"s1.swap(s9) :"<<endl;
s1.swap(s9);
cout<<"s1: "<<endl;
printSet(s1);
cout<<"s9: "<<endl;
printSet(s9);
//lower_bound,upper_bound,equal_range(略)
}


自定义比较函数

         使用insert将元素插入到集合中去的时候,集合会根据设定的比较函数奖该元素放到该放的节点上去。在定义集合的时候,如果没有指定比较函数,那么采用默认的比较函数,即按键值从小到大的顺序插入元素。但在很多情况下,需要自己编写比较函数。

编写比较函数有两种方法。

(1)如果元素不是结构体,那么可以编写比较函数。下面的程序比较规则为按键值从大到小的顺序插入到集合中。

#include<iostream>
#include<set>
using namespace std;
struct mycomp
{ //自定义比较函数,重载“()”操作符
	bool operator() (const int &a, const int &b)
	{
		if(a != b)
			return a > b;
		else
			return a > b;
	}
};
int main()
{
	set<int, mycomp> s; //采用比较函数mycomp
	s.insert(5); //第一次插入5,可以插入
	s.insert(1);
	s.insert(6);
	s.insert(3);
	s.insert(5); //第二次插入5,重复元素,不会插入
	set<int,mycomp>::iterator it;
	for(it = s.begin(); it != s.end(); it++)
		cout << *it << " ";
	cout << endl;
	return 0;
}
/*
运行结果:6 5 3 1  
*/

(2)如果元素是结构体,那么可以直接把比较函数写在结构体内。

#include<iostream>
#include<set>
#include<string>
using namespace std;
struct Info
{
	string name;
	double score;
	bool operator < (const Info &a) const // 重载“<”操作符,自定义排序规则
	{
		//按score由大到小排序。如果要由小到大排序,使用“>”即可。
		return a.score < score;
	}
};
int main()
{
	set<Info> s;
	Info info;

	//插入三个元素
	info.name = "Jack";
	info.score = 80;
	s.insert(info);
	info.name = "Tom";
	info.score = 99;
	s.insert(info);
	info.name = "Steaven";
	info.score = 60;
	s.insert(info);

	set<Info>::iterator it;
	for(it = s.begin(); it != s.end(); it++)
		cout << (*it).name << " : " << (*it).score << endl; 
	return 0;
}
/*
运行结果:
Tom : 99
Jack : 80
Steaven : 60
*/







集合的用法

#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
 
int main()
{
       int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
       set<int> S( a, a + 9 );
      
       int b[] = { 3, 6, 8, 9 };
       set<int> S2( b, b + 4 );
      
       set<int>::iterator site;
 
       set<int> Su;
       set<int> Si;
       set<int> Sd;
       set<int> Ssd;
      
       //交集
       set_intersection( S.begin(), S.end(),
                                   S2.begin(), S2.end(),
                                   inserter( Si, Si.begin() ) );
                                  
       //并集
       set_union( S.begin(), S.end(),
                     S2.begin(), S2.end(),
                        inserter( Su, Su.begin() ) );
                       
       //差集
       set_difference( S.begin(), S.end(),
                                S2.begin(), S2.end(),
                                   inserter( Sd, Sd.begin() ) );
      
       //对称差集
       set_symmetric_difference( S.begin(), S.end(),
                                                S2.begin(), S2.end(),
                                                 inserter( Ssd, Ssd.begin() ) );
                                                
      
       site = Si.begin();
       cout<<"the intersection of S and S2 is : ";
       while( site != Si.end() )
       {
              cout<< *site <<" ";
              ++ site;
       }
       cout<<endl;
      
       site = Su.begin();
       cout<<"the union of S and S2 is : ";
       while( site != Su.end() )
       {
              cout<< *site <<" ";
              ++ site;
       }
       cout<<endl;
      
       site = Sd.begin();
       cout<<"the difference of S and S2 is : ";
       while( site != Sd.end() )
       {
              cout<< *site <<" ";
              ++ site;
       }
       cout<<endl;
      
       site = Ssd.begin();
       cout<<"the symmetric difference of S and S2 is : ";
       while( site != Ssd.end() )
       {
              cout<< *site <<" ";
              ++ site;
       }
       cout<<endl;
      
       return 0;
}