STL体系结构与内核分析-2-STL体系结构基础介绍(侯捷)--笔记

STL体系结构与内核分析(侯捷)

2.STL体系结构基础介绍

STL设计方式与OO(面向对象)不同的地方,OO鼓励数据和处理数据的方法都放在类里,而STL的数据在容器里,操作数据的方法在其他部件里(模板编程)。

迭代器:泛化指针

STL六大部件:
在这里插入图片描述

示例代码:

#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>


using namespace std;


int main() {
    int ia[6] = {27, 210, 12, 40, 109, 93};
    //vector 容器
    //allocator 分配器
    vector<int, allocator<int>> vi(ia, ia + 6);
    //输出不小于40的数字的个数
    //count_if 算法
    //begin(),end()迭代器
    //less 仿函数
    //bind2nd 适配器(这里是仿函数适配器)
    cout << count_if(vi.begin(), vi.end(), not1(bind2nd(less<int>(), 40)));
    return 0;
}
f = std::bind1st( functor, v); 'f( x)'等价于'functor( v, x)'
f = std::bind2nd( functor, v); 'f( x)'等价于'functor( x, v)'

复杂度取决于数据分布等,具体情况具体分析(所以集成了多种不同算法,而不是唯一的最优算法)

容器特性:前闭后开,空间不一定是连续的

伪代码:


Container<T> C;
...
Container<T>::iterator ite = c.begin();
for (; ite != c.end(); ++ite)
...

range-based for statement(since C++11)–for不同用法

#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>


using namespace std;


int main() {
    vector<int, allocator<int>> v{1, 2, 3};
    cout << "t1:";
    for (int i : {1, 2, 3})
        cout << i << " ";
    cout << endl;
    cout << "t2:";
    for (auto i : v)
        cout << i << " ";
    cout << endl;
    cout << "t3:";
    for (auto &i : v) {//传引用
        i *= 2;
        cout << i << " ";
    }
    cout << endl;
    cout << "t4:";
    for (auto i : v)
        cout << i << " ";
    cout << endl;
    return 0;
}

输出:

t1:1 2 3
t2:1 2 3
t3:2 4 6
t4:2 4 6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值