介绍STL之前,先回顾一下数据结构。
数据结构是什么?
A means of representing data to achieve efficiency in terms of
– time complexity: to minimize runtime
– memory complexity: to minimize memory usage
数据结构是能(在时间上和空间上)比较有效地表示数据的一种手段。
A means of demonstrating relationships between data elements
是能表示数据间的关系的一种手段。
A means of enforcing a processing order(强调了一种处理的顺序)
A means of modeling real-world problems(对现实世界中的问题建模)
数据结构分类(3类)
线性结构、树状结构、图
这里直说线性结构。
1. 线性结构
Linked Lists vs. Arrays
区别在于:
(1) Placement and access of storage
– arrays: use contiguous storage + random access (连续存储、随机访问)
– linked lists: use non-contiguous storage + sequential access(非连续存储、顺序访问)
(2) Volume of storage
– Arrays: fixed size(尽管动态数组看起来可以增加大小,但其实每次new出来的int [] 也只是一个固定大小…)
– Linked lists: expand and contract as needed(想变就变)
下面简介STL。
什么是STL?
STL = Standard Template Library
– based (heavily) on template programming(居于模板的编程)– with a guarantee of performance
A general-purpose library of generic algorithms and data structures in C++
– container classes– generic algorithms
– other components (ex: iterators)
Part of the ISO Standard C++ Library
为什么要用STL?
– data-structures already well-written and thoroughly debugged
– fit more meaningful stuff on one page
– STL data structures grow automatically
Portable code( 代码“轻”,不是很懂)
STL的7大部件
– containers
– iterators
– algorithms
– functional objects (functors)
– adaptors
– allocators
– traits
基本的STL(一级部件)
– referencing devices similar to the pointers to the individual elements used in data structures
– class templates which implement many of the classic data structures
– template functions that implement frequently used algorithms (i.e., sorting, searching, etc.)
STL的容器(按里面数据的存储方式吧)可分为哪两大类?
线性容器和关联容器。
1. 线性容器
string,vector,list
2. 关联容器
set,map
使用STL所带来的问题
STL implementation was 40% slower than hand-optimized version
– STL: used deque
– hand coded: used “circular buffer” array
Application with STL list ~5% slower than custom list
However, spending several days debugging the hand-coded version usually not worth it
Use STL for rapid prototyping
尽管引入STL开发出来的程序,其执行速率一般会比“纯手写的原生态”代码(的执行速率)慢40%,(但我相信也比java的快…)
但是一旦使用STL开发,开发的速率就会起飞了!
泛型编程
Often missing in basic programming courses, even in OOP courses
The most successful example of the GP implementation is STL
– until 1994, STL became part of C++ standard library
STL is not merely a collection of functions and classes, but a collection of templates or patterns.
STL不仅仅是一堆函数和类,还是一个模板(或模式)的集合。
GP is orthogonal to OOP --> new language level
– no encapsulation, (almost) no inheritance
泛型编程与OOP是正交的,层面上就不是一个东西……
一种新的语言层次。
没有封装,甚至没有继承。