STL 中常用的 vector,map,set,sort 用法

版权声明:本文为博主原创文章,未经博主允许不得转载。vasttian https://blog.csdn.net/u012860063/article/details/24435211

                     STL中的常用的vector,map,set,sort,pair用法


C++的标准模板库(Standard Template Library,简称STL)是一个容器和算法的类库。容器往往包含同一类型的数据。STL中比较常用的容器是vector,set和map,比较常用的算法有Sort等。
.
一. vector

1.声明:
           一个vector类似于一个动态的一维数组。
           vector中可以存在重复的元素!
           vector<int> a;          // 声明一个元素为int类型的vector a
           vectot<MyType> a;       // 声明一个元素为MyType类型的vector a
          这里的声明的a包含0个元素,既a.size()的值为0,但它是动态的,其大小会随着数据的插入和删除改变而改变。
           vector<int> a(100, 0);  // 这里声明的是一个已经存放了100个0的整数vector
2.向量操作
常用函数:
          a.size();                // 返回vector的大小,即包含的元素个数
          a.pop_back();            // 删除vector末尾的元素,vector大小相应减一
          a.push_back();           // 用于在vector的末尾添加元素
          a.back();                // 返回vector末尾的元素
          a.clear();               // 将vector清空,vector大小变为0
其他访问方式:
          cout<<a[5]<<endl;
          cout<<a.at(5)<<endl;
以上区别在于后者在访问越界时会抛出异常,而前者不会。
3.遍历
          (1).     for(vector<datatype>::iterator it=a.begin(); it!=a.end(); it++)
                     cout<<*it<<endl;
          (2).     for(int i = 0; i < a.size(); i++)
                     cout<<a[i]<<endl;
1.vector 的数据的存入和输出:
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
	int i = 0;
    vector<int> v;
    for(i = 0; i < 10; i++)
	{
		v.push_back( i );       //把元素一个一个存入到vector中
	}
    /* v.clear()*/ //对存入的数据清空
	for( i = 0; i < v.size(); i++ ) //v.size() 表示vector存入元素的个数
	{
		cout << v[ i ] << "  "; //把每个元素显示出来
	}
	cout << endl;
}


1. push_back()        在数组的最后添加一个数据
2. pop_back()         去掉数组的最后一个数据
3. at()               得到编号位置的数据
4. begin()            得到数组头的指针
5. end()              得到数组的最后一个单元+1的指针
6. front()            得到数组头的引用
7. back()             得到数组的最后一个单元的引用
8. max_size()         得到vector最大可以是多大
9. capacity()         当前vector分配的大小
10.size()             当前使用数据的大小
11.resize()           改变当前使用数据的大小,如果它比当前使用的大,则填充默认值
12.reserve()          改变当前vecotr所分配空间的大小
13.erase()            删除指针指向的数据项
14.clear()            清空当前的vector
15.rbegin()           将vector反转后的开始指针返回(其实就是原来的end-1)
16.rend()             将vector反转构的结束指针返回(其实就是原来的begin-1)
17.empty()            判断vector是否为空
18.swap()             与另一个vector交换数据

二. map


Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性
map内部的实现自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能。
下面举例说明什么是一对一的数据映射。比如一个班级中,每个学生的学号跟他的姓名就存在着一一映射的关系,这个模型用map可能轻易描述,
很明显学号用int描述,姓名用字符串描述(本篇文章中不用char *来描述字符串,而是采用STL中string来描述),
下面给出map描述代码:

1.声明方式:
           map<int, string> mapStudent; 或map<string,int> mapStudent; 
/*两者均是正确声明方式,当然效果是不一样的*/

2.数据的插入
在构造map容器后,我们就可以往里面插入数据了。这里讲三种插入数据的方法:
第一种:用insert函数插入pair数据
           map<int, string> mapStudent;
           mapStudent.insert(pair<int, string>(1,“student_one”));
第二种:用insert函数插入value_type数据
           map<int, string> mapStudent;
           mapStudent.insert(map<int, string>::value_type (1,"student_one"));
   mapStudent.insert(make_pair(1, "student_one"));
第三种:用数组方式插入数据
           map<int, string> mapStudent;
           mapStudent[1] = “student_one”;
           mapStudent[2] = “student_two”;
/*
如果是
#include <map>
map<string, int> mapStudent;
string s;
插入就用m[s]++;

*/
以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,用insert函数插入数据,在数据的插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是不能再插入这个数据的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值;

3.map的大小
在往map里面插入了数据,我们怎么知道当前已经插入了多少数据呢,可以用size函数:
             int nSize = mapStudent.size();

4.数据的遍历
第一种:应用前向迭代器
           
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
    cout<<iter->first<<"  "<<iter->second<<end;



第二种:应用反向迭代器
           
map<int, string>::reverse_iterator iter;
for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)
    cout<<iter->first<<"  "<<iter->second<<end;



第三种:用数组方式
 
int nsize = mapStudent.size()
for(int nIndex = 1; nIndex <= nSize; nIndex++)
     cout<<mapStudent[nIndex]<<end;



例如:
#include<map>
#include<string>
#include<iostream>
using namespace std;

int main()
{
    map<string,int>  m;
    m["a"]=1;
    m["b"]=2;
    m["c"]=3;
    map<string,int>::iterator it;
    for(it=m.begin();it!=m.end();++it)
        cout<<"key: "<<it->first <<" value: "<<it->second<<endl;
    return   0;
}

 
map<string,int>::iterator it;   定义一个迭代指针it。 
it->first 为索引键值,it->second 为值。


5. 数据的查找(包括判定这个关键字是否在map中出现)
这里给出三种数据查找方法:
第一种:用count函数来判定关键字是否出现,但是无法定位数据出现位置
第二种:用find函数来定位数据出现位置它返回的一个迭代器,
当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器。

例如:
int main()
{
            map<int, string> mapStudent;
            mapStudent.insert(pair<int, string>(1, “student_one”));
            mapStudent.insert(pair<int, string>(2, “student_two”));
            mapStudent.insert(pair<int, string>(3, “student_three”));
            map<int, string>::iterator iter;
            iter = mapStudent.find(1);
            if(iter != mapStudent.end())
            {
                   cout<<”Find, the value is ”<<iter->second<<endl;
            }
            else
            {
               cout<<”Do not Find”<<endl;
            }
}


第三种:这个方法用来判定数据是否出现
lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器)
upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器)
例如:map中已经插入了1,2,3,4的话,如果lower_bound(2)的话,返回的2,而upper-bound(2)的话,返回的就是3
equal_range函数返回一个pair,pair里面第一个变量是Lower_bound返回的迭代器,pair里面第二个迭代器是Upper_bound返回的迭代器,如果这两个迭代器相等的话,则说明map中不出现这个关键字,程序说明
mapPair = mapStudent.equal_range(2);
if(mapPair.first == mapPair.second)
      
            cout<<”Do not Find”<<endl;

6. 数据的清空与判空
清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map

7. 数据的删除
这里要用到erase函数,它有三个重载了的函数
迭代器删除 
            iter = mapStudent.find(1);
            mapStudent.erase(iter);
用关键字删除
            int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0
用迭代器,成片的删除
            一下代码把整个map清空
            mapStudent.earse(mapStudent.begin(), mapStudent.end());
            //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合

8.其他一些函数用法
这里有swap,key_comp,value_comp,get_allocator等函数;


例如:

map <int, vector<int> > mm;
第二个键值是一个vector容器,就可以存多个值,和二维数组a[ ] [ ],差不多了!
个数 : int len = mm[tt].size();
访问其中的值,直接可以用mm[i] [j]访问;
vector<int> ::iterator iter;
iter = lower_bound(mm[tt].begin(), mm[tt].end(), l);

三. set

set是集合,set中不会包含重复的元素,这是和vector的区别。
定义:
定义一个元素为整数的集合a,可以用 set<int> a;
1,set的含义是集合,它是一个有序的容器,里面的元素都是排序好的,支持插入,删除,查找等操作,就像一个集合一样。所有的操作都是严格在logn时间之内完成的,效率非常高。 set和multiset的区别是:set插入的元素不能相同,但是multiset可以相同。

set的基本操作:
1. begin()         返回指向第一个元素的迭代器
2. clear()         清除所有元素
3. count()         返回某个值元素的个数
4. empty()         如果集合为空,返回true
5. end()           返回指向最后一个元素的迭代器
6. equal_range()   返回集合中与给定值相等的上下限的两个迭代器
7. erase()         删除集合中的元素
8. find()          返回一个指向被查找到元素的迭代器
9. get_allocator() 返回集合的分配器
10.insert()        在集合中插入元素
11.lower_bound()   返回指向大于(或等于)某值的第一个元素的迭代器
12.key_comp()      返回一个用于元素间值比较的函数
13.max_size()      返回集合能容纳的元素的最大限值
14.rbegin()        返回指向集合中最后一个元素的反向迭代器
15.rend()          返回指向集合中第一个元素的反向迭代器
16.size()          集合中元素的数目
17.swap()          交换两个集合变量
18.upper_bound()   返回大于某个值元素的迭代器
19.value_comp()    返回一个用于比较元素间的值的函数

set的遍历
代码如下:
set<int>ss;
        set<int>::iterator it;
        for(it = ss.begin(); it != ss.end(); it++)
        {
            printf("%d ",*it);
        }


lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,而不会破坏容器顺序的第一个位置,而这个位置标记了一个大于等于value 的值。  
例如,有如下序列:  ia[]={12,15,17,19,20,22,23,26,29,35,40,51};
用值21调用lower_bound(),返回一个指向22的iterator。用值22调用lower_bound(),也返回一个指向22的iterator。
iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值> key的第一个元素。
-------------------------------------------------------------------------------------------------

函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

举例如下:

一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标

pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。

pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。

pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。

所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~

返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置

-------------------------------------------------------------------------------------------------
集合的并,交和差
set_union(a.begin(),a.end(),b.begin(),b.end(),insert_iterator<set<int> >(c,c.begin()));
set_intersection(a.begin(),a.end(),b.begin(),b.end(),insert_iterator<set<int> >(c,c.begin()));
set_difference(a.begin(),a.end(),b.begin(),b.end(),insert_iterator<set<int> >(c,c.begin()));


(注意在此前要将c清为空集)。
注意:
为了实现集合的快速运算,set的实现采用了平衡二叉树,因此,set中的元素必须是可排序的。如果是自定义的类型,那在定义类型的同时必须给出运算符<的定义
struct node
{
    int x, y;
    bool operator < (const struct node tmp) const
    {
        if(x == tmp.x)
            return y < tmp.y ;
        return x < tmp.x ;
    }
} ;


四. Sort

                  sort顾名思义就是排序
用法:
单关键字:
                 对于vector a来说
                 sort(a,a+n); //n=a.size()       将a中元素按递增排序。
多关键字:
                 我们也可以利用类pair
                 vector< pair<int,int> > a; // 注意这里两个> >中间必须有一个空格,否则编译器会当是运算符>>
例如:
int N,x,y;
cin >> N;
for(int i = 0; i < N; ++i) 
{
	cin >> x >> y;
	a.push_back(make_pair(x,y)); // make_pair用于创建pair对象
}
sort(&a[0], &a[N]);</span>

注意:
对于我们自己定义的类或结构,系统一般不能做比较运算,需要我们自己定义相应的运算符

bool cmp(MyType x, MyType y)
{
	if(x < y)
		return true;
	if(x >= y)
		return false;
}




map是一个关联容器,里面存放的是键值对,容器中每一元素都是pair类型,通过map的insert()方法来插入元素(pair类型)。template <class T1,class T2>
  pair<T1,T2> make_pair (T1 x, T2 y)
  {
    return ( pair<T1,T2>(x,y) );
  }


pair的类型:

    pair 是 一种模版类型。每个pair 可以存储两个值。这两种值无限制。也可以将自己写的struct的对象放进去。。

    pair<string,int> p;

    pair<int ,int > p;

    pair<double,int> p;

    都可以。。。  

    std::pair主要的作用是将两个数据组合成一个数据,两个数据可以是同一类型或者不同类型。例如std::pair<int,float> 或者 std::pair<double,double>等。pair实质上是一个结构体,其主要的两个成员变量是first和second,这两个变量可以直接使用。初始化一个pair可以使用构造函数,也可以使用std::make_pair函数。

应用:如果一个函数有两个返回值 的话,如果是相同类型,就可以用数组返回,如果是不同类型,就可以自己写个struct ,但为了方便就可以使用 c++ 自带的pair ,返回一个pair,其中带有两个值。除了返回值的应用,在一个对象有多个属性的时候 ,一般自己写一个struct ,如果就是两个属性的话,就可以用pair 进行操作。。。
          应用pair 可以省的自己写一个struct 。。。如果有三个属性的话,其实也是可以用的pair 的 ,极端的写法 pair <int ,pair<int ,int > >写法极端。(后边的两个 > > 要有空格,否则就会是 >> 位移运算符)
    
   pair<int ,int >p (5,6);
   pair<int ,int > p1= make_pair(5,6);
   pair<string,double> p2 ("aa",5.0);
   pair <string ,double> p3 = make_pair("aa",5.0);
   有这两种写法来生成一个pair。
   如何取得pair的值呢。。
   每个pair 都有两个属性值 first 和second    cout<<p1.first<<p1.second; 注意是属性值而不是方法。

      一般make_pair都使用在需要pair做参数的位置,可以直接调用make_pair生成pair对象。make_pair是根据2个参数类型推导出pair的2个模板参数类型的。另一个使用的方面就是pair可以接受隐式的类型转换,这样可以获得更高的灵活度。但是这样会出现如下问题:例如有如下两个定义:

<span style="font-size:18px;">std::pair<int, float>(1, 1.1);
std::make_pair(1, 1.1);
</span>

     其中第一个的second变量是float类型,而make_pair函数会将second变量都转换成double类型。这个问题在编程是需要引起注意。下面是一段pair与make_pair的例子程序:

#include <iostream>
#include <utility>
#include <string>
using namespace std;
int main ()
{
        pair <string,double> product1 ("tomatoes",3.25);
	pair <string,double> product2;
	pair <string,double> product3;

	product2.first ="lightbulbs"; // type of first is string
	product2.second =0.99; // type of second is double
	
	product3 = make_pair ("shoes",20.0);
		
	cout <<"The price of "<< product1.first <<" is $"<< product1.second <<"\n";
	cout <<"The price of "<< product2.first <<" is $"<< product2.second <<"\n";
	cout <<"The price of "<< product3.first <<" is $"<< product3.second <<"\n";
	return 0;
}


map是一个关联容器,里面存放的是键值对,容器中每一元素都是pair类型,通过map的insert()方法来插入元素(pair类型)。


mapStudent.insert(map<int, string>::value_type (1,"student_one"));

mapStudent.insert(make_pair(1, "student_one"));


猜你喜欢

转载自blog.csdn.net/u012860063/article/details/24435211