2.STL体系结构基础介绍(侯捷STL学习笔记)

本文深入解析C++标准模板库(STL)的六大核心组件:容器、分配器、算法、迭代器、适配器及仿函式。通过实例代码展示了各组件的基本用法与相互间的协作关系,帮助读者理解STL的内部机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、六大部件

》容器(Containers)

》分配器(Allocators)

》算法(Algorithm)

》迭代器(Iterators)

》适配器(Adapters)

》仿函式(Functors)

代码 ------- 简单实现6种部件的代码

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
int main() {
  int a[6] = {27 , 210 , 40 , 12 , 47 , 92};

  /*
    allocator<int> 是 分配器 但是通常vector有
    默认的分配器 所以通常省略
    ========= 分配器
  */
  /*vector ======= 容器*/
  vector<int,allocator<int> > vi(a , a + 6);//此时vi 得到了 a[0] - a[1]的值

  //count_if 是 计量函数 计算符合标准的元素有几个    ========= 算法
  //范围是 vi.begin()-----vi.end()    ======== 迭代器
  //bind2nd(less<int>() , 40) --- 小于40的元素    ========= 仿函式 + 适配器
  //not1() ---- 否定作用    ========= 仿函式 + 适配器
  cout << count_if(vi.begin(),vi.end(),
                not1(bind2nd(less<int>(), 40))) << endl;//不小于四十的数量 ---> 大于等于四十的数量 ----> 4
  return 0;
}


运行的截图

二、容器

#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char const *argv[]) {
  vector<int> c;

  //向容器中增加元素
  c.push_back(0);
  c.push_back(1);
  c.push_back(2);
  c.push_back(3);
  c.push_back(4);

  // 让迭代器一开始指到容器的起始位置
  //c.begin()指的位置是第一个元素位置 c.end()指的是最后一个元素的下一个位置
  vector<int>::iterator ite = c.begin();

  //通过游标来循环查看容器元素
  for(;ite != c.end();ite++)
    cout << *ite << " ";
  return 0;
}


运行的结果:0 1 2 3 4

三、C++的特殊迭代器

#include <bits/stdC++.h>
using namespace std;
int main() {
	
	//按照 2-9-3-7-5的顺序遍历 
   for(int i : { 2 , 9 , 3 , 7 , 5 })
     cout << i << " ";
    
    cout << endl;
    
    int a[6] = {1,2,3,4,5,6}; 
	for(int i : { 2 , 6 , 3 , 4 , 5 })
	    cout << a[i - 1] << " ";
	
	//创建容器 并且加入元素	
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(3);
	
	cout << endl;
	//顺序输出v里面的元素 
	for(auto y : v)
	    cout << y << endl;
	
	cout << endl;
	//顺序改变y的值并输出  (&) 
	for(auto& y : v){
		y *= 3; 
		cout << y << endl;
	}
	  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值