STL标准模板库《实战案例汇总》

本文涉及的产品
智能开放搜索 OpenSearch行业算法版,1GB 20LCU 1个月
实时计算 Flink 版,5000CU*H 3个月
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: STL标准模板库《实战案例汇总》

第一部分,STL基础

一、STL简介

STLStandard Template Library,标准模板库)是惠普实验室开发的一系列软件的统称。它是由Alexander StepanovMeng LeeDavid R Musser在惠普实验室工作时所开发出来

的。现在虽说它主要出现在C++中,但在被引入C++之前该技术就已经存在了很长的一段时间。

 

STL的代码从广义上讲分为三类:algorithm(算法)、container(容器)和iterator(迭代器),几乎所有的代码都采用了模板类和模版函数的方式,这相比于传统的由函数和类

 

组成的库来说提供了更好的代码重用机会。在C++标准中,STL被组织为下面的13个头文件<algorithm><deque><functional><iterator><vector>、<list>、<map>、

<memory><numeric><queue><set><stack><utility>


二、算法

大家都能取得的一个共识是函数库对数据类型的选择对其可重用性起着至关重要的作用。举例来说,一个求方根的函数,在使用浮点数作为其参数类型的情况下的可重用性肯定比

使用整型作为它的参数类性要高。而C++通过模板的机制允许推迟对某些类型的选择,直到真正想使用模板或者说对模板进行特化的时候,STL就利用了这一点提供了相当多的有用

算法。它是在一个有效的框架中完成这些算法的——你可以将所有的类型划分为少数的几类,然后就可以在模版的参数中使用一种类型替换掉同一种类中的其他类型。

STL提供了大约100个实现算法的模版函数,比如算法for_each将为指定序列中的每一个元素调用指定的函数,stable_sort以你所指定的规则对序列进行稳定性排序等等。这样一来

,只要我们熟悉了STL之后,许多代码可以被大大的化简,只需要通过调用一两个算法模板,就可以完成所需要的功能并大大地提升效率。

 

算法部分主要由头文件<algorithm><numeric><functional>组成。

<algorithm>是所有STL头文件中最大的一个(尽管它很好理解),它是由一大堆模版函数组成的,可以认为每个函数在很大程度上都是独立的,其中常用到的功能范围涉及到比较、交换、查找、遍历操作、复制、修改、移除、反转、排序、合并等等。

 

<numeric>体积很小,只包括几个在序列上面进行简单数学运算的模板函数,包括加法和乘法在序列上的一些操作。 

<functional>中则定义了一些模板类,用以声明函数对象。

 

三、容器

在实际的开发过程中,数据结构本身的重要性不会逊于操作于数据结构的算法的重要性,当程序中存在着对时间要求很高的部分时,数据结构的选择就显得更加重要。

经典的数据结构数量有限,但是我们常常重复着一些为了实现向量、链表等结构而编写的代码,这些代码都十分相似,只是为了适应不同数据的变化而在细节上有所出入。STL容器

就为我们提供了这样的方便,它允许我们重复利用已有的实现构造自己的特定类型下的数据结构,通过设置一些模版类,STL容器对最常用的数据结构提供了支持,这些模板的参数

允许我们指定容器中元素的数据类型,可以将我们许多重复而乏味的工作简化。

 

容器部分主要由头文件<vector>,<list>,<deque>,<set>,<map>,<stack><queue>组成。对于常用的一些容器和容器适配器(可以看作由其它容器实现的容器),可以通过下表总结一下它们和相应头文件的对应关系。 

向量(vector) 连续存储的元素<vector>

列表(list)       由节点组成的双向链表,每个结点包含着一个元素<list>

双队列(deque) 连续存储的指向不同元素的指针所组成的数组<deque>

集合(set) 由节点组成的红黑树,每个节点都包含着一个元素,节点之间以某种作用于元素对的谓词排列,没有两个不同的元素能够拥有相同的次序 <set>

多重集合(multiset) 允许存在两个次序相等的元素的集合 <set>

(stack) 后进先出的值的排列 <stack>

队列(queue) 先进先出的执的排列 <queue>

优先队列(priority_queue) 元素的次序是由作用于所存储的值对上的某种谓词决定的的一种队列 <queue>

映射(map) {键,值}对组成的集合,以某种作用于键对上的谓词排列 <map>

多重映射(multimap) 允许键对有相等的次序的映射 <map>

 

四、迭代器 

下面要说的迭代器从作用上来说是最基本的部分,可是理解起来比前两者都要费力一些(至少笔者是这样)。软件设计有一个基本原则,所有的问题都可以通过引进一个间接层来

简化,这种简化在STL中就是用迭代器来完成的

概括来说,迭代器在STL中用来将算法和容器联系起来,起着一种黏和剂的作用。几乎STL提供的所有算法都是通过迭代器存取元素序列进行工作的,每一个容器都定义了其本身所专有的迭代器,用以存取容器中的元素。

 

迭代器部分主要由头文件<utility>,<iterator><memory>组成。

<utility>是一个很小的头文件,它包括了贯穿使用在STL中的几个模板的声明,

<iterator>中提供了迭代器使用的许多方法,而对于<memory>的描述则十分的困难,它以不同寻常的方式为容器中的元素分配存储空间,同时也为某些算法执行期间产生的临时对象提供机制,<memory>中的主要部分是模板类allocator,它负责产生所有容器中的默认分配器。

  对于之前不太了解STL的读者来说,上面的文字只是十分概括地描述了一下STL的框架,对您理解STL的机制乃至使用STL所起到的帮助微乎甚微,这不光是因为深入STL需要对C++的高级应用有比较全面的了解,更因为STL的三个部分算法、容器和迭代器三部分是互相牵制或者说是紧密结合的。从概念上讲最基础的部分是迭代器,可是直接学习迭代器会遇到许多抽象枯燥和繁琐的细节,然而不真正理解迭代器又是无法直接进入另两部分的学习的(至少对剖析源码来说是这样)。可以说,适应STL处理问题的方法是需要花费一定的时间的,但是以此为代价,STL取得了一种十分可贵的独立性,它通过迭代器能在尽可能少地知道某种数据结构的情况下完成对这一结构的运算,所以下决心钻研STL的朋友们千万不要被一时的困难击倒。其实STL运用的模式相对统一,只要适应了它,从一个STL工具到另一个工具,都不会有什么大的变化。

对于STL的使用,也普遍存在着两种观点。第一种认为STL的最大作用在于充当经典的数据结构和算法教材,因为它的源代码涉及了许多具体实现方面的问题。第二种则认为STL的初衷乃是为了简化设计,避免重复劳动,提高编程效率,因此应该是“应用至上”的,对于源代码则不必深究。笔者则认为分析源代码和应用并不矛盾,通过分析源代码也能提高我们对其应用的理解,当然根据具体的目的也可以有不同的侧重。


第二部分,案例实战分析

暂且举几个非常容易理解的程序源码:

#include <iostream>
#include <vector>
using namespace std;
int main(){
    vector<int>vi;
    int a;
    while(true)
    {
    cout<<"输入一个整数,按0停止输入:";
    cin>>a;
    if(a==0)
    break;
    vi.push_back(a);   
    vector<int>::iterator iter;
    for(iter=vi.begin();iter!=vi.end();++iter)
    cout<<*iter;      
    }
    return 0;
    }


#include <iostream> 
#include <string>
#include <vector> 
using namespace std; 
int main(){
string str="shiyang"; 
vector <string> vecstr; 
vecstr.push_back(str);
vector <string> ::iterator iter= vecstr.begin(); 
cout<<*iter<<endl;
return 0;
}


#include   <stdlib.h>   
#include   <windows.h>   
#include   <conio.h>   
#include   <map>   //STL
#include   <functional> //STL  
#include   <algorithm>   //STL
#include   <iostream>   
using namespace std;   
typedef  map<int,int*> m_iip;   
typedef  map<int,char*> m_icp;   
class  f_c{   
  int _i;   
  public:   
  f_c(int i):_i(i){
          
  }   
  void operator()(m_iip::value_type ite)   
  {   
  cout<<_i++<<"\t"<<ite.first<<" shi"<<endl;   
  }   
  void operator()(m_icp::value_type ite)  
  {   
  cout<<_i++<<"\t"<<ite.first<<" yang"<<endl;  
  }   
  };   
  void f(int i,int c)   
  {   
      
  }   
  int main(int argc,char* argv[]){
  m_iip  iip;   
  m_icp  icp;   
  int i=0;   
  iip.insert(make_pair(34,&i));   
  iip.insert(make_pair(67,&i));   
  iip.insert(make_pair(5,&i));   
  iip.insert(make_pair(342,&i));    
  char d=0;   
  icp.insert(make_pair(12,&d));   
  icp.insert(make_pair(54,&d));   
  icp.insert(make_pair(6,&d));   
  icp.insert(make_pair(92,&d));   
  for_each(iip.begin(),iip.end(),f_c(8));   
  for_each(icp.begin(),icp.end(),f_c(65));//   
  return 0;   
  }


#include <iostream>
#include <list>
#include <numeric>
#include <algorithm>
using namespace std;
//创建一个list容器的实例LISTINT
typedef list<int> LISTINT;

//创建一个list容器的实例LISTCHAR
typedef list<int> LISTCHAR;

int main(){
    //--------------------------
    //用list容器处理整型数据
    //--------------------------
    //用LISTINT创建一个名为listOne的list对象
    LISTINT listOne;
    //声明i为迭代器
    LISTINT::iterator i;

    //从前面向listOne容器中添加数据
    listOne.push_front (2);
    listOne.push_front (1);

    //从后面向listOne容器中添加数据
    listOne.push_back (3);
    listOne.push_back (4);

    //从前向后显示listOne中的数据
    cout<<"listOne.begin()--- listOne.end():"<<endl;
    for (i = listOne.begin(); i != listOne.end(); ++i)
        cout << *i << " ";
    cout << endl;

    //从后向前显示listOne中的数据
LISTINT::reverse_iterator ir;
    cout<<"listOne.rbegin()---listOne.rend():"<<endl;
    for (ir =listOne.rbegin(); ir!=listOne.rend();ir++) {
        cout << *ir << " ";
    }
    cout << endl;

    //使用STL的accumulate(累加)算法
    int result = accumulate(listOne.begin(), listOne.end(),0);
    cout<<"Sum="<<result<<endl;
    cout<<"------------------"<<endl;

    //--------------------------
    //用list容器处理字符型数据
    //--------------------------

    //用LISTCHAR创建一个名为listOne的list对象
    LISTCHAR listTwo;
    //声明i为迭代器
    LISTCHAR::iterator j;

    //从前面向listTwo容器中添加数据
    listTwo.push_front ('A');
    listTwo.push_front ('B');

    //从后面向listTwo容器中添加数据
    listTwo.push_back ('x');
    listTwo.push_back ('y');

    //从前向后显示listTwo中的数据
    cout<<"listTwo.begin()---listTwo.end():"<<endl;
    for (j = listTwo.begin(); j != listTwo.end(); ++j)
        cout << char(*j) << " ";
    cout << endl;

    //使用STL的max_element算法求listTwo中的最大元素并显示
    j=max_element(listTwo.begin(),listTwo.end());
    cout << "The maximum element in listTwo is: "<<char(*j)<<endl;
}


#include <iostream>
#include <list>

using namespace std;
typedef list<int> INTLIST;

//从前向后显示list队列的全部元素
void put_list(INTLIST list, char *name)
{
    INTLIST::iterator plist;

    cout << "The contents of " << name << " : ";
    for(plist = list.begin(); plist != list.end(); plist++)
        cout << *plist << " ";
    cout<<endl;
}

//测试list容器的功能
int main(){
//list1对象初始为空
    INTLIST list1;   
    //list2对象最初有10个值为6的元素 
    INTLIST list2(10,6); 
    //list3对象最初有9个值为6的元素 
    INTLIST list3(list2.begin(),--list2.end()); 

    //声明一个名为i的双向迭代器
    INTLIST::iterator i;

    //从前向后显示各list对象的元素
    put_list(list1,"list1");
    put_list(list2,"list2");
    put_list(list3,"list3");
    
//从list1序列后面添加两个元素
list1.push_back(2);
list1.push_back(4);
cout<<"list1.push_back(2) and list1.push_back(4):"<<endl;
    put_list(list1,"list1");

//从list1序列前面添加两个元素
list1.push_front(5);
list1.push_front(7);
cout<<"list1.push_front(5) and list1.push_front(7):"<<endl;
    put_list(list1,"list1");

//在list1序列中间插入数据3个9 
list1.insert(++list1.begin(),3,9);
cout<<"list1.insert(list1.begin(),3,9):"<<endl;
    put_list(list1,"list1");

//测试引用类函数
cout<<"list1.front()="<<list1.front()<<endl;
cout<<"list1.back()="<<list1.back()<<endl;

//从list1序列的前后各移去一个元素
list1.pop_front();
list1.pop_back();
cout<<"list1.pop_front() and list1.pop_back():"<<endl;
    put_list(list1,"list1");

//清除list1中的第2个元素
list1.erase(++list1.begin());
cout<<"list1.erase(++list1.begin()):"<<endl;
    put_list(list1,"list1");

//对list2赋值并显示
list2.assign(8,1);
cout<<"list2.assign(8,1):"<<endl;
    put_list(list2,"list2");

//显示序列的状态信息
cout<<"list1.max_size(): "<<list1.max_size()<<endl;
cout<<"list1.size(): "<<list1.size()<<endl;
cout<<"list1.empty(): "<<list1.empty()<<endl;

//list序列容器的运算
    put_list(list1,"list1");
    put_list(list3,"list3");
cout<<"list1>list3: "<<(list1>list3)<<endl;
cout<<"list1<list3: "<<(list1<list3)<<endl;

//对list1容器排序
list1.sort();
    put_list(list1,"list1");
    
//结合处理
list1.splice(++list1.begin(), list3);
    put_list(list1,"list1");
    put_list(list3,"list3"); 
}


第三部分,头文件汇总

C++头文件一览

C、传统 C++

#include <assert.h>    设定插入点

#include <ctype.h>    字符处理

#include <errno.h>     定义错误码

#include <float.h>    浮点数处理

#include <fstream.h>   文件输入/输出

#include <iomanip.h>    参数化输入/输出

#include <iostream.h>   数据流输入/输出

#include <limits.h>    定义各种数据类型最值常量

#include <locale.h>    定义本地化函数

#include <math.h>     定义数学函数

#include <stdio.h>    定义输入/输出函数

#include <stdlib.h>    定义杂项函数及内存分配函数

#include <string.h>    字符串处理

#include <strstrea.h>   基于数组的输入/输出

#include <time.h>     定义关于时间的函数

#include <wchar.h>     宽字符处理及输入/输出

#include <wctype.h>    宽字符分类

标准 C++ 

#include <algorithm>     通用算法

#include <bitset>      位集容器

#include <cctype>

#include <cerrno>

#include <clocale>

#include <cmath>

#include <complex>     复数类

#include <cstdio>

#include <cstdlib>

#include <cstring>

#include <ctime>

#include <deque>      双端队列容器

#include <exception>    异常处理类

#include <fstream>

#include <functional>    定义运算函数(代替运算符)

#include <limits>

#include <list>       线性列表容器

#include <map>       映射容器

#include <iomanip>

#include <ios>      基本输入/输出支持

#include <iosfwd>    输入/输出系统使用的前置声明

#include <iostream>

#include <istream>     基本输入流

#include <ostream>     基本输出流

#include <queue>       队列容器

#include <set>       集合容器

#include <sstream>     基于字符串的流

#include <stack>      堆栈容器    

#include <stdexcept>    标准异常类

#include <streambuf>   底层输入/输出支持

#include <string>     字符串类

#include <utility>     通用模板类

#include <vector>     动态数组容器

#include <cwchar>

#include <cwctype>

C99 增加

#include <complex.h>  复数处理

#include <fenv.h>    浮点环境

#include <inttypes.h>  整数格式转换

#include <stdbool.h>   布尔环境

#include <stdint.h>   整型环境

#include <tgmath.h>  通用类型数学宏

相关文章
|
4月前
|
存储 C++ 容器
C++STL(标准模板库)处理学习应用案例
【4月更文挑战第8天】使用C++ STL,通过`std:vector`存储整数数组 `{5, 3, 1, 4, 2}`,然后利用`std::sort`进行排序,输出排序后序列:`std:vector<int> numbers; numbers = {5, 3, 1, 4, 2}; std:sort(numbers.begin(), numbers.end()); for (int number : numbers) { std::cout << number << " "; }`
38 2
|
30天前
|
存储 算法 编译器
[C++] STL简介
[C++] STL简介
23 1
|
1月前
|
算法 编译器 程序员
STL 简介(标准模板库)
STL 简介(标准模板库)
51 9
|
3月前
|
存储 算法 C++
C++一分钟之-标准模板库(STL)简介
【6月更文挑战第21天】C++ STL是高效通用的算法和数据结构集,简化编程任务。核心包括容器(如vector、list)、迭代器、算法(如sort、find)和适配器。常见问题涉及内存泄漏、迭代器失效、效率和算法误用。通过示例展示了如何排序、遍历和查找元素。掌握STL能提升效率,学习过程需注意常见陷阱。
48 4
|
2月前
|
存储 算法 数据处理
【C++】STL简介
**STL是C++标准库的关键部分,源于Alexander Stepanov的泛型编程研究。它提供了数据结构(如vector、list)和算法,是高效、通用的软件框架。STL始于惠普,后由SGI发展,现已成为C++1998标准的一部分并不断进化。它包括容器、迭代器、算法、仿函数、配接器和分配器六大组件,带来高效性、通用性和可扩展性,但也存在性能开销和学习难度。学习STL涉及理解底层数据结构、用法、实现和实践。推荐[cplusplus.com](https://cplusplus.com)作为学习资源。**
|
2月前
|
存储 算法 数据处理
|
4月前
|
算法 安全 Linux
【C++】STL简介(了解)
【C++】STL简介(了解)
|
4月前
|
算法 安全 Linux
【c++】STL简介(了解)
【c++】STL简介(了解)
【c++】STL简介(了解)
|
4月前
|
算法 安全 Linux
【C++】—— STL简介(了解)
【C++】—— STL简介(了解)
|
4月前
|
算法 Linux C语言
(C++)STL简介
(C++)STL简介
49 0