You are on page 1of 15

Generic Programming STL

Generic Programming STL


jjhou@ccca.nctu.edu.tw
http://www.jjhou.com
=>

1.
2.
3.
4.
5.

STL
Iterators Traits
Containers
Generic Algorithms Function Objects
Adaptors

2000.02
2000.03
2000.04
2000.05
2000.06

OOObject Oriented
OO
Generic Programming

C++ Template, Generic programming, STL


1968 Doug McIlroy "Mass Produced Software Components"
ICcomponents
software -- --

--

container container
classes data members container classes member
functionscoupling
interoperability

Generic Programming STL

OO OO

C++ template
template

function body class body


instantiation
C++ function templates class templates members
templates member templatesnested
STL
function template
#include <iostream>
using namespace std;
template <class Type>
Type mymin(Type a, Type b) {
return a < b ? a : b;
}

mymin() a b less-than operator


Type operator<
class rect
{
friend ostream& operator<<(ostream& os, const rect& rhs);
public:
rect(int w, int h) : _w(w), _h(h)
{ _area = _w * _h; }
bool operator<(const rect& rhs) const
{ return _area < rhs._area; }
private:
int _w, _h, _area;
};
ostream& operator<<(ostream& os, const rect& rhs)
{
os << '(' << rhs._w << ',' << rhs._h << ')' << endl;
return os;
}

Generic Programming STL

int main()
{
// int mymin(int, int);
cout << mymin(10, 20) << endl; // 10
// double mymin(double, double);
cout << mymin(30.0, 20.0) << endl; // 20
rect r1(3,5), r2(5,7);
// rect mymin(rect, rect);
cout << mymin(r1, r2) << endl; // (3,5)
}

class template
template <typename Type>
class Queue {
public:
Queue() { /* ... */ };
~Queue() { /* ... */ };
Type& remove();
void add( const Type & );
bool is_empty();
bool is_full();
private:
// ....
};

class template Queue


Queue<int> qi;
Queue< complex<double> > qc;
Queue<string> qs;

int, complex<double> string Queue class


template C++ C++ Primer 3/e, by
Lippman & Lajoie 10 16
templates
template
Alexander StepanovSTL
STL stack
push pop stackpushing

Generic Programming STL

stack stack pushing


stack
reusable
Lego

STL
STLSTL

C++ template :)

GenericGenericityObject OrientedSTLStandard
Template Library MFCMicrosoft Foundation Classes

STL
STL components
MFC VCL Windows
STL STL Generic Paradigm
requirements concepts
models refinementsAlexander
StepanovSTL
STL concepts
classes
iterators adaptors function objects

adaptable

Generic Programming STL

STL STL
STL STL STL

STL 1
STL Alexander Stepanov 1979 Bjarne Stroustrup C++
David R. Musser 1971
AdaAlex Musser
1987 Ada library Ada C++
C++ template Alex
C/C++

component library
Alex AT&T Hewlett-Packard Palo Alto
C C++ 1992 Meng Lee Alex
Bell Andrew Koenig 1993 Alex 11
ANSI/ISO C++ Alex
Waterloo C++ Standard

1 STL Dr Dobb's Journal 1995 "Alexander


Stepanov and STL"

STL C++ Standard C++ Standard Library C++


STL
STL C++ <vector>, <list>,<functional>, <algorithm>,
<iterator> .h C++ C++ Standard
.h Inprise C++Builder
.h
C++ (1) .h (2) Visual C++
.h .h GNU C++
.h .h stl_xxx.h

Generic Programming STL

C++ STL
Microsoft VC6P.J. Plauger
Inprise C++Builder4Rogue Wave Software, Inc.
GNU C++ egcs-2.91.57Silicon Graphics Computer Systems, Inc

STL Hewlett-Packard Company Alexander Stepanov Meng


Lee

STL
http://www.sgi.com/Technology/STL/
http://www.stlport.org/

STL

STL
STL
STL
STL
STL
STL C++ template

STL
code
STL
STL components
1. containers vector, list,deque, set, map
2. algorithms sort, search,copy, eraseSTL 70
3. iterator containers algorithms
iterator STL containers
algorithms
4. function object "call operator"
classesC/C++ function objectSTL 15
function objects

Generic Programming STL

5. adaptorcontainers function object STL queue


stack container adaptor function object
function adaptor functor container container adaptor
iterator iterator adaptor
6. allocatorSTL allocator

generic programming STL


STL

STL STL
STL Concepts Modeling Refinement
traits STL
STL

STL
STL STL
STL

STL
1815 waterloo in Belgium C++ 1994
waterloo in Ontario, USA C++
STL
STL

STL containers STL containers


STL algorithms for_each()STL containers class
int
STL STL C++ Standard
Library std namespace
using directive
using namespace std;

Generic Programming STL

\ STL
STL

----------------------------------algorithms
<algorithm>

<numeric> 2
vector
<vector>
list
<list>
deque
<deque>
stack
<stack>
queue
<queue>
priority queue
<queue>
map
<map>
set
<set>
multimap
<map>
multiset
<set>
function objects
<functional>
iterator adaptor
<iterator>
2accumulate(), adjacent_difference(),
partial_sum(), inner_product().

int ia[] = { 1, 3, 2, 4 };

containers containers
container
container iterator
int C++ iterator
C++ Standard Inprise C++Builder 4.0

list<int> ilist(ia, ia+4);


vector<int> ivector(ia, ia+4);
deque<int> ideque(ia, ia+4);
stack<int> istack(ideque);
queue<int> iqueue(ideque);
priority_queue<int> ipqueue(ia, ia+4);
set<int> iset(ia, ia+4);

map /
map<string, int> simap; //
simap[string("1")] = ia[0];
simap[string("2")] = ia[1];
simap[string("3")] = ia[2];

string int
// ("1", 1)
// ("2", 3)
// ("3", 2)

Generic Programming STL

simap[string("4")] = ia[3]; // ("4", 4)

containers for_each() STL algorithms


iterators containers
begin() end() member functions iterators
container begin() end() while
for_each()
STL function object
cout STL
function objects
for_each(ilist.begin(), ilist.end(), pfi);
// 1 3 2 4
for_each(ivector.begin(), ivector.end(), pfi); // 1 3 2 4
for_each(ideque.begin(), ideque.end(), pfi);
// 1 3 2 4
for_each(iset.begin(), iset.end(), pfi);
// 1 2 3 4
while(!istack.empty()) {
cout << istack.top() << " ";
istack.pop();
}
while(!iqueue.empty()) {
cout << iqueue.front() << " ";
iqueue.pop();
}
while(!ipqueue.empty()) {
cout << ipqueue.top() << " ";
ipqueue.pop();
}

// 4 2 3 1

// 1 3 2 4

// 4 3 2 1

stackqueuepriority queue
set
map map /key/value
first second

map<string, int>::iterator iter; // iterator


for (iter=simap.begin(); iter!=simap.end(); ++iter)
cout << iter->first << " " << iter->second << " "; // 1 1 2 3 3 2 4 4
}

containers iterators vector<int> iterator


vector<int>::iterator iter;

Generic Programming STL

10

vector<int>::const_iterator citer;

list<string> iterator
list<string>::iterator iter;
list<string>::const_iterator citer;

STL algorithm accumulate() ilist


STL function objectmultiplies<int>
// 1 * 3 * 2 * 4.
cout << accumulate(ilist.begin(), ilist.end(),
1, multiplies<int>()) << endl;

// 24

STL algorithm inner_product() ilist iset


// 0 + 1*1 + 3*2 + 2*3 + 4*4.
cout << inner_product(ilist.begin(), ilist.end(), //
iset.begin(),
//
0 )
//
<< endl;
// 29

STL
STL
list list
list < list <string> > mylist;

list vector pairpair string,


int
list < vector < pair < string, int > > > mylist;

generic algorithms for_each()function object modulus<int>function adaptor bind2nd()container


list<int>
// BCB4 : bcc32 test.cpp
// GCC : g++ -o test.exe test.cpp
#include <functional>
#include <list>
#include <iostream>
#include <algorithm>
using namespace std;
template <typename T>
void print_elements(T elem)

// function template

Generic Programming STL

11

{ cout << elem << " "; }


void (*pfi)(int) = print_elements;

//

void main()
{
int ia[7] = {0,1,2,3,4,5,6};
list<int> ilist(ia, ia+7);
// list
for_each(ilist.begin(), ilist.end(), pfi); // 0 1 2 3 4 5 6
ilist.push_back(7);
ilist.push_back(0);
ilist.push_back(7);
ilist.push_back(9);
for_each(ilist.begin(), ilist.end(), pfi); // 0 1 2 3 4 5 6 7 0 7 9
ilist.remove_if(bind2nd(modulus<int>(), 2)); //
for_each(ilist.begin(), ilist.end(), pfi); // 0 2 4 6 0
}

// CB4 : bcc32 test.cpp


// VC6 : cl -GX test.cpp
// GCC : g++ -o test.exe test.cpp
#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>
#include <iterator>
using namespace std;
int main()
{
string file_name;
cout << "please enter a file to open: ";
cin >> file_name;
if ( file_name.empty() || !cin ) { //
cerr << "unable to read file name\n";
return -1;
}
ifstream infile( file_name.c_str());
if ( ! infile ) { //
cerr << "unable to open " << file_name << endl;
return -2;
}

Generic Programming STL

12

// iterators
// string
// end-of-stream
// cout string " "
istream_iterator< string > ins( infile ), eos;
ostream_iterator< string > outs( cout, " " );
copy( ins, eos, outs ); // copy
}

stream iterator

STL
concept, model refinement, range
predicate, iterator, adaptor
STL
[Austern99]

concept, model
conceptrequirementsconcept class
template C++
concept C++ concept concepts
STL
conecpt modelconcept
type T concept C model T C
concept types concept Input Iterator char*, int*, float*
wrap classes type T concept C model T
C
concepts algorithms
formal template arguments

STL concepts

Generic Programming STL

13

1. Assignabletype X concept Assignable model type X object


type X object x, y Assignable x, y

X x(y)
x = y
tmp = y, x = tmp

type X Assignable model copy constructor


2. Default Constructible type T Default Constructible model default
constructor type T object
T()

type T
T t;

C++ int void Default Constructible


3. Equality Comparable type T Equality Comparable model
type T objects
x==y

x!=y

4. LessThan Comparable type T LessThan Comparable model


T object T object
x < y

x > y

regular type Assignable, Default Constructible,Equality Comparable concepts


model regular type x assign y x==y

basic C++ types regular typesint concepts model


STL types regular types

Generic Programming STL

14

refinements
concept C2 concept C1 C2 C1
refinement
Modeling refinement concepts types

1. Reflexivity concept C refinement


2. Containment type X concept C2 model C2 concept C1
refinement X C1 model
3. Transitivity C3 C2 refinement C2 C1 refinement
C3 C1 refinement
type concepts model concept concept refinement

range

range [first, last) [first, last) dereferenceable


first last first last
[first, last) [A, A+N) rangeempty range [A, A) [A+N, A)
range
ranges
1. p [p, p) range
2. [first, last) range [first+1, last) range
3. [first, last) range mid first last
mid [first, mid) [mid, last) ranges.
4. [first, mid) [mid, last) ranges [first, last)
ranges

iterator traits Traits STL


STL iterators
STL containersSTL algorithms
STL

Generic Programming STL

15

1. "Alexander Stepanov and STL", Dr. Dobb's Journal, Mar. 1995.


2. [Austern99] "Generic Programming and the STL" by Matthew H. Austern, AW, 1999
3. [Lippman98] "C++ Primer" by Lippman & Lajoie, AW, 1998
4. [Musser96] "STL Tutorial and Reference Guide" by David R. Musser, AW, 1996

Windows SDK/MFC C/C++

You might also like