Sunteți pe pagina 1din 8

STL Quick Reference – Version 1.

32 [A4] July 10, 2009 1

1 Notations 2.2.2 Members & Operators S:iterator S::erase(S::const iterator first, void // move x’s [xFirst,xLast) before pos
x post erased S::const iterator last); list::splice (iterator pos,
• The symbol const for const. X::X(); void S::push back(const S::value type& x ); listhTi& x,
• The symbol x for function returned value. X::X(const X&); iterator xFirst,
void S::pop back(); iterator xLast); +7.2
• Template class parameters lead by outlined X::~X();
character. For example: T, Key, Compare.
S::reference S::front(); void list::remove(const T& value);
X& X::operator=(const X&);
S::const reference S::front() void list::remove if (Predicate pred);
const ;
Interpreted in template definition context.
X::iterator X::begin();
• Sometimes class, typename dropped. X::const iterator X::begin() const ; S::reference S::back(); // after call: ∀ this iterator p, ∗p 6= ∗(p + 1)
• Template class parameters dropped, X::iterator X::end(); S::const reference S::back() const ; void list::unique(); // remove repeats
thus C sometimes used instead of ChTi. X::const iterator X::end() const ; void // as before but, ¬binPred(∗p, ∗(p + 1))
• “See example” by +, its output by ' à. X::reverse iterator X::rbegin(); 2.4 Vector list::unique(B inaryPredicate binPred);
X::const reverse iterator X::rbegin() const ; #include <vector> // Assuming both this and x sorted
X::reverse iterator X::rend(); void list::merge(listhTi& x );
2 Containers X::const reverse iterator X::rend() const ; templatehclass T,
A lloc=allocatori
// merge and assume sorted by cmp
void list::merge(listhTi& x, Compare cmp);
class
X::size type X::size() const ; class vector;
2.1 Pair X::size type X::max size() const ; void list::reverse();
#include <utility> bool X::empty() const ; See also 2.2 and 2.3. void list::sort();
void list::sort(Compare cmp);
void X::swap(X& x); size type vector::capacity() const ;
templatehclass T1, class T2i void vector::reserve(size type n);
void X::clear();
struct pair {
T1 first; T2 second; vector::reference 2.7 Sorted Associative
2.2.3 Comparison Operators vector::operator[ ](size type i); Here A any of
pair() {}
vector::const reference {set, multiset, map, multimap}.
pair(const T1& a, const T2& b): Let, X v, w. X may also be pair (2.1). vector::operator[ ](size type i) const ;
first(a), second(b) {} }; v == w v != w
+ 7.1. 2.7.1 Types
v < w v > w
2.1.1 Types For A=[multi]set, columns are the same
v <= w v >= w 2.5 Deque
pair::first type All done lexicographically and xbool. A::key type A::value type
#include <deque>
pair::second type A::key compare A::value compare
templatehclass T,
2.1.2 Functions & Operators 2.3 Sequence Containers class A lloc=allocatori
2.7.2 Constructors
See also 2.2.3. S is any of {vector, deque, list} class deque; A::A(Compare c=Compare())
pairhT1,T2i Has all of vector functionality (see 2.4). A::A(A::const iterator first,
make pair(const T1&, const T2&); 2.3.1 Constructors A::const iterator last,
S::S(S::size type n,
void deque::push front( const T& x ); Compare c=Compare());
2.2 Containers — Common const S::value type& t); void deque::pop front();
2.7.3 Members
S::S(S::const iterator first,
Here X is any of
S::const iterator last); +7.2, 7.3 2.6 List A::key compare A::key comp() const ;
{vector, deque, list,
set, multiset, map, multimap} #include <list> A::value compare A::value comp() const ;
2.3.2 Members A::iterator
2.2.1 Types templatehclass T, A::insert(A::iterator
A lloc=allocatori
S::iterator // inserted copy hint,
class const A::value type& val);
S::insert(S::iterator before, class list;
X::value type const S::value type& val); void A::insert(A::iterator first,
X::reference See also 2.2 and 2.3. A::iterator last);
S::iterator // inserted copy
X::const reference void list::pop front();
S::insert(S::iterator before, A::size type // # erased
X::iterator S::size type nVal, A::erase(const A::key type& k );
void list::push front(const T& x );
X::const iterator const S::value type& val); void A::erase(A::iterator p);
void // move all x (&x 6= this) before pos
X::reverse iterator S::iterator // inserted copy void A::erase(A::iterator first,
list::splice(iterator pos, listhTi& x ); +7.2
X::const reverse iterator S::insert(S::iterator before, A::iterator last);
void // move x’s xElemPos before pos
X::difference type S::const iterator first, A::size type
S::const iterator last); list::splice (iterator pos,
X::size type A::count(const A::key type& k ) const ;
listhTi& x,
Iterators reference value type (See 6). S:iterator S::erase(S::iterator position); iterator xElemPos); +7.2 A::iterator A::find(const A::key type& k ) const ;

Yotam Medini
c 1998-2009 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
2 STL Quick Reference – Version 1.32 [A4] July 10, 2009

A::iterator 2.10.2 Members multimap::const iterator void


A::lower bound(const A::key type& k ) const ; multimap::lower bound( queue::push(const Container::value type& x);
const multimap::key type& k ) const ;
A::iterator map::map( void queue::pop();
A::upper bound(const A::key type& k ) const ; const Compare& cmp=Compare()); multimap::const iterator
Container::value type&
const
pairhA::iterator, A::iteratori // see 4.3.1 pairhmap::iterator, booli // bool = if new multimap::upper bound(
const multimap::key type& k ) const ; queue::front() const ;
Container::value type& queue::front();
A::equal range(const A::key type& k ) const ; map::insert(const map::value type& x );
pairhmultimap::const iterator,
T& map:operator[ ](const map::key type&); Container::value type&
multimap::const iteratori const
2.8 Set map::const iterator multimap::equal range( queue::back() const ;
const multimap::key type& k ) const ;
map::lower bound(
#include <set> const map::key type& k ) const ; Container::value type& queue::back();
templatehclass Key, map::const iterator
map::upper bound(
3 Container Adaptors Comparision Operators
class Compare=lesshKeyi, const map::key type& k ) const ;
bool operator= =(const queue& q0,
A lloc=allocatori
const queue& q1);
class pairhmap::const iterator, map::const iteratori 3.1 Stack Adaptor
class set; bool operator<(const queue& q0,
map::equal range( const queue& q1);
#include <stack>
See also 2.2 and 2.7.
set::set(const Compare& cmp=Compare());
const map::key type& k ) const ;
templatehclass T, 3.3 Priority Queue
class Container=dequehTi i
pairhset::iterator, booli // bool = if new Example
#include <queue>
set::insert(const set::value type& x ); typedef map<string, int> MSI; class stack;

Default constructor. Container must have


MSI nam2num;
nam2num.insert(MSI::value_type("one", 1)); templatehclass T,
2.9 Multiset nam2num.insert(MSI::value_type("two", 2)); back(), push back(), pop back(). So vector, class Container=vectorhTi,
class Compare=lesshTi i
nam2num.insert(MSI::value_type("three", 3)); list and deque can be used.
#include <set> int n3 = nam2num["one"] + nam2num["two"]; bool stack::empty() const ; class priority queue;
templatehclass Key,
cout << n3 << " called ";
Container::size type stack::size() const ;
class Compare=lesshKeyi, Container must provide random access iterator
for (MSI::const_iterator i = nam2num.begin();
i != nam2num.end(); ++i)
class A lloc=allocatori
void
stack::push(const Container::value type& x);
if ((*i).second == n3) and have empty(), size(), front(), push back()
{cout << (*i).first << endl;} and pop back(). So vector and deque can be
class multiset; void stack::pop(); used.

See also 2.2 and 2.7. 3 called three const Container::value type& Mostly implemented as heap.
multiset::multiset( stack::top() const ;
const Compare& cmp=Compare()); 2.11 Multimap 3.3.1 Constructors
Container::value type& stack::top();
multiset::multiset( #include <map> Comparision Operators explicit priority queue::priority queue(
InputIterator first, const Compare& comp=Compare());

InputIterator last,
bool operator= =(const stack& s0,
templatehclass Key, class T, const stack& s1); priority queue::priority queue(
const Compare& cmp=Compare()); class Compare=lesshKeyi, bool operator<( const InputIterator first,
class A lloc=allocatori
stack& s0,
multiset::iterator // inserted copy const stack& s1); InputIterator last,
class multimap; const Compare& comp=Compare());
multiset::insert(const multiset::value type& x );
See also 2.2 and 2.7. 3.2 Queue Adaptor
3.3.2 Members
2.10 Map #include <queue>
2.11.1 Types bool priority queue::empty() const ;
#include <map>
Key,Ti Container::size type
templatehclass Key, class T,
multimap::value type // pairh const
templatehclass T, priority queue::size() const ;
class Container=dequehTi i
class Compare=lesshKeyi, 2.11.2 Members
const Container::value type&
class queue;
class A lloc=allocatori priority queue::top() const ;
class map; multimap::multimap( Default constructor. Container must have Container::value type& priority queue::top();
See also 2.2 and 2.7.
const Compare& cmp=Compare()); empty(), size(), back(), front(), push back()
void priority queue::push(
const Container::value type& x);
and pop front(). So list and deque can be
multimap::multimap( used.
2.10.1 Types InputIterator first, void priority queue::pop();
InputIterator last,
bool queue::empty() const ;
map::value type // pairhconst Key,Ti const Compare& cmp=Compare()); Container::size type queue::size() const ; No comparision operators.

Yotam Medini
c 1998-2009 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
STL Quick Reference – Version 1.32 [A4] July 10, 2009 3

4 Algorithms // x bi-pointing to first binPred-mismatch O utputIterator // ∀ski ∈ Sk ri = bop(s1i , s2i ) ForwardIterator // as above but using pred
pairhInputIterator1, InputIterator2i transform(InputIterator1 first1, remove if (ForwardIterator first,
#include <algorithm> mismatch(InputIterator1 first1, InputIterator1 last1, ForwardIterator last,
InputIterator1 last1, InputIterator2 first2, Predicate pred);
STL algorithms use iterator type parameters. InputIterator2 first2, O utputIterator result, O utputIterator // x past last copied
B inaryPredicate binPred);
Their names suggest their category (See 6.1).
For abbreviation, the clause — B inaryOperation bop); remove copy(InputIterator first,
template hclass Foo, ...i is dropped. The
bool
void replace(ForwardIterator
InputIterator last,
equal(InputIterator1 first1, first,
O utputIterator result,
outlined leading character can suggest the InputIterator1 last1, ForwardIterator last, const T& value);
InputIterator2 first2);
const T& oldVal,
template context.
Note: When looking at two sequences: const T& newVal); O utputIterator // as above but using pred
bool remove copy if (InputIterator first,
equal(InputIterator1
S1 = [first1 , last1 ) and S2 = [first2 , ?) or
S2 = [?, last2 ) — caller is responsible that first1, void InputIterator last,
function will not overflow S2 . InputIterator1 last1, replace if (ForwardIterator first, O utputIterator result,
InputIterator2 first2, ForwardIterator last, Predicate pred);
4.1 Query Algorithms B inaryPredicate binPred); Predicate& pred,
const T& All variants of unique template functions
// [first2 , last2 ) v [first1 , last1 ) newVal); remove consecutive (binPred-) duplicates. Thus
Function // f not changing [first, last) ForwardIterator1 O utputIterator // x result2 + #[first, last)
usefull after sort (See 4.3).
for each(InputIterator first, search(ForwardIterator1 first1, ForwardIterator // [x,last) gets repetitions
InputIterator last, replace copy(InputIterator
ForwardIterator1 last1,
first,
InputIterator unique(ForwardIterator first,
Function f ); +7.4 ForwardIterator2 first2,
last,
ForwardIterator last);
O utputIterator result,
InputIterator // first i so i==last or *i==val ForwardIterator2 last2); const T& oldVal, ForwardIterator // as above but using binPred
find(InputIterator first, // [first2 , last2 ) vbinPred [first1 , last1 ) const T& newVal); unique(ForwardIterator first,
InputIterator last, ForwardIterator1 ForwardIterator last,
constT val); +7.2 search(ForwardIterator1 first1, O utputIterator // as above but using pred B inaryPredicate binPred);
InputIterator // first i so i==last or pred(i) ForwardIterator1 replace copy if (InputIterator
O utputIterator // x past last copied
last1, first,
find if (InputIterator first, ForwardIterator2 InputIterator
unique copy(InputIterator
first2, last,
InputIterator last, ForwardIterator2 O utputIterator first,
InputIterator
last2, result,
Predicate B inaryPredicate Predicate& last,
O utputIterator result,
pred); +7.7 binPred); pred,
const T& newVal);
ForwardIterator // first duplicate 4.2 Mutating Algorithms const T& result);
adjacent find(ForwardIterator first, void fill(ForwardIterator first, O utputIterator // as above but using binPred
ForwardIterator last); O utputIterator // x first2 + (last1 − first1 ) ForwardIterator last, unique copy(InputIterator first,
ForwardIterator // first binPred-duplicate copy(InputIterator first1, const T& value); InputIterator last,
adjacent find(ForwardIterator first, InputIterator last1, O utputIterator result,
O utputIterator first2); void fill n(ForwardIterator B inaryPredicate binPred);
ForwardIterator last,
first,
S ize
B inaryPredicate binPred);
n,
// x last2 − (last1 − first1 ) void
B idirectionalIterator2 reverse(B idirectionalIterator first,
const T& value);
void // n = # equal val
count(ForwardIterator first, copy backward( void // by calling gen() B idirectionalIterator last);
ForwardIterator last, B idirectionalIterator1 first1, generate(ForwardIterator first, O utputIterator // x past last copied
B idirectionalIterator1 last1, ForwardIterator last, reverse copy(B idirectionalIterator first,
B idirectionalIterator2 last2);
const T val,
S ize& n); G enerator gen); B idirectionalIterator last,
void // n = # satisfying pred void swap(T& x, T& y);
void // n calls to gen() O utputIterator result);
count if (ForwardIterator first, ForwardIterator2 // x first2 + #[first1 , last1 ) generate n(ForwardIterator first, void // with first moved to middle
ForwardIterator last, swap ranges(ForwardIterator1 first1, S ize n, rotate(ForwardIterator first,
Predicate pred, ForwardIterator1 last1, G enerator gen); ForwardIterator middle,
S ize& n); ForwardIterator2 first2); All variants of remove and unique return ForwardIterator last);
// x bi-pointing to first != O utputIterator // x result + (last1 − first1 ) iterator to new end or past last copied. O utputIterator // first to middle position
pairhInputIterator1, InputIterator2i transform(InputIterator first, ForwardIterator // [x,last) is all value rotate copy(ForwardIterator first,
mismatch(InputIterator1 first1, InputIterator last, remove(ForwardIterator first, ForwardIterator middle,
InputIterator1 last1, O utputIterator result, ForwardIterator last, ForwardIterator last,
InputIterator2 first2); UnaryOperation op); +7.6 const T& value); O utputIterator result);

Yotam Medini
c 1998-2009 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
4 STL Quick Reference – Version 1.32 [A4] July 10, 2009

void RandomAccessIterator bool // S1 ⊇ S2


includes(InputIterator1
equal range returns iterators pair that
random shuffle( partial sort copy( first1,
RandomAccessIterator first,
lower bound and upper bound return.
InputIterator InputIterator1
pairhForwardIterator,ForwardIteratori
first, last1,
RandomAccessIterator last); InputIterator InputIterator2
equal range(ForwardIterator first,
last, first2,
RandomAccessIterator InputIterator2
ForwardIterator last,
void // rand() returns double in [0, 1) resultFirst, last2);
random shuffle( RandomAccessIterator resultLast, bool // as above but using comp
RandomAccessIterator first, Compare
const T& value);
comp); includes(InputIterator1 first1,
RandomAccessIterator last, Let n = position − first, nth element pairhForwardIterator,ForwardIteratori InputIterator1 last1,
RandomGenerator rand); partitions [first, last) into: L = [first, position), equal range(ForwardIterator first, InputIterator2 first2,
ForwardIterator last, InputIterator2
B idirectionalIterator // begin with true
en , R = [position + 1, last) such that last2,
Compare
∀l ∈ L, ∀r ∈ R l 6> en ≤ r.
partition(B idirectionalIterator first,
const T& value, comp);
void Compare
B idirectionalIterator last, O utputIterator // S1 ∪ S2 , xpast end
comp);
nth element(
Predicate pred); RandomAccessIterator first, + 7.5 set union(InputIterator1 first1,
B idirectionalIterator // begin with true RandomAccessIterator position, InputIterator1 last1,
stable partition( RandomAccessIterator last); 4.3.2 Merge InputIterator2 first2,
B idirectionalIterator first, InputIterator2 last2,
O utputIterator
void // as above but using comp(ei , ej ) Assuming S1 = [first1 , last1 ) and
B idirectionalIterator last, nth element( S2 = [first2 , last2 ) are sorted, stably merge them result);
Predicate pred); RandomAccessIterator first, into [result, result + N ) where N = |S1 | + |S2 |. O utputIterator // as above but using comp
RandomAccessIterator position, O utputIterator set union(InputIterator1 first1,
4.3 Sort and Application RandomAccessIterator last, merge(InputIterator1 first1, InputIterator1 last1,
Compare comp); InputIterator1 InputIterator2 first2,
void sort(RandomAccessIterator
last1,
first, InputIterator2 InputIterator2 last2,
RandomAccessIterator
first2,
last); 4.3.1 Binary Search
InputIterator2 last2, O utputIterator result,
void sort(RandomAccessIterator first, bool O utputIterator result); Compare comp);
RandomAccessIterator last, binary search(ForwardIterator first, O utputIterator O utputIterator // S1 ∩ S2 , xpast end
+7.3 Compare comp); ForwardIterator last, merge(InputIterator1 first1, set intersection(InputIterator1 first1,
void
const T& value); InputIterator1 last1, InputIterator1 last1,
stable sort(RandomAccessIterator first, bool InputIterator2 first2, InputIterator2 first2,
RandomAccessIterator last); binary search(ForwardIterator first, InputIterator2 last2, InputIterator2 last2,
void ForwardIterator last, O utputIterator result, O utputIterator result);
stable sort(RandomAccessIterator first,
const T& value, Compare comp); O utputIterator // as above but using comp
RandomAccessIterator last, Compare comp); set intersection(InputIterator1 first1,
void // ranges [first,middle) [middle,last)
Compare comp); ForwardIterator inplace merge( // into [first,last) InputIterator1 last1,
void // [first,middle) sorted, lower bound(ForwardIterator first, B idirectionalIterator first, InputIterator2 first2,
partial sort( // [middle,last) eq-greater ForwardIterator last, B idirectionalIterator middle, InputIterator2 last2,
RandomAccessIterator first, const T& value); B idirectionalIterator last); O utputIterator result,
RandomAccessIterator middle, ForwardIterator void // as above but using comp
Compare comp);
RandomAccessIterator last); lower bound(ForwardIterator first, inplace merge( O utputIterator // S1 \ S2 , xpast end
void // as above but using comp(ei , ej ) ForwardIterator last, B idirectionalIterator first, set difference(InputIterator1 first1,
partial sort(
const T& value, B idirectionalIterator middle, InputIterator1 last1,
RandomAccessIterator first, Compare comp); B idirectionalIterator last, InputIterator2 first2,
RandomAccessIterator middle, ForwardIterator Compare comp); InputIterator2 last2,
RandomAccessIterator last, upper bound(ForwardIterator first, O utputIterator result);
Compare comp); ForwardIterator last, 4.3.3 Functions on Sets O utputIterator // as above but using comp
RandomAccessIterator // post last sorted set difference(InputIterator1 first1,
const T& value);
Can work on sorted associcative containers (see
partial sort copy( ForwardIterator 2.7). For multiset the interpretation of — InputIterator1 last1,
InputIterator first, upper bound(ForwardIterator first, union, intersection and difference is by: InputIterator2 first2,
InputIterator last, ForwardIterator last, maximum, minimum and substraction of InputIterator2 last2,
RandomAccessIterator resultFirst, const T& value,
occurrences respectably.
O utputIterator result,
RandomAccessIterator resultLast); Compare comp); Let Si = [firsti , lasti ) for i = 1, 2. Compare comp);

Yotam Medini
c 1998-2009 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
STL Quick Reference – Version 1.32 [A4] July 10, 2009 5

O utputIterator // S1MS2 , xpast end 4.3.5 Min and Max 4.3.7 Lexicographic Order O utputIterator // rk = sk − sk−1 for k > 0
set symmetric difference( adjacent difference( // r0 = s0
InputIterator1 first1, const T& min(const T& x0, const T& x1); bool lexicographical compare( InputIterator first,
InputIterator1 last1, InputIterator1 first1, InputIterator last,
InputIterator2 first2, const T& min(const T& x0, InputIterator1 last1, O utputIterator result);
InputIterator2 last2, const T& x1,
InputIterator2 first2,
O utputIterator Compare comp); O utputIterator // as above but using binop
result); InputIterator2 last2); adjacent difference(
O utputIterator // as above but using comp const T& max(const T& x0, const T& x1); bool lexicographical compare( InputIterator first,
set symmetric difference(
InputIterator1 first1, InputIterator
InputIterator1
const T& max(const T& x0, last,
first1,
InputIterator1 last1, O utputIterator
InputIterator1
const T& x1, result,
last1,
Compare comp); InputIterator2 first2, B inaryOperation
InputIterator2
binop);
first2,
InputIterator2 last2,
InputIterator2 last2, ForwardIterator Compare
O utputIterator
comp);
result, min element(ForwardIterator first, 5 Function Objects
Compare comp); ForwardIterator last); 4.4 Computational
4.3.4 Heap ForwardIterator #include <functional>
min element(ForwardIterator first, #include <numeric>
void // (last − 1) is pushed ForwardIterator last, templatehclass A rg, class Resulti
push heap(RandomAccessIterator T // [first,last) +7.6
P
first, Compare comp);
accumulate(InputIterator
RandomAccessIterator first, struct unary function {
typedef A rg argument type;
last);
ForwardIterator InputIterator last,
void // as above but using comp
max element(ForwardIterator first, typedef Result result type;}
push heap(RandomAccessIterator
T initVal);
ForwardIterator last);
first,
RandomAccessIterator last, T // as above but using binop
Compare accumulate(InputIterator
Derived unary objects:
comp); ForwardIterator first,
struct negatehTi;
void // first is popped max element(ForwardIterator first, InputIterator last,
struct logical nothTi;
pop heap(RandomAccessIterator first, ForwardIterator last, T initVal, + 7.6
RandomAccessIterator last); Compare comp); B inaryOperation binop);
T // i e1i × e2i for eki ∈ Sk , (k = 1, 2) templatehclass A rg1, class A rg2,
P
void // as above but using comp
pop heap(RandomAccessIterator first,
4.3.6 Permutations inner product(InputIterator1 first1, class Resulti
RandomAccessIterator last, InputIterator1 last1, struct binary function {
Compare comp);
To get all permutations, start with ascending
InputIterator2 first2, typedef A rg1 first argument type;
typedef A rg2 second argument type;
sequence end with descending.
T initVal);
typedef Result result type;}
void // [first,last) arbitrary ordered
make heap(RandomAccessIterator first,
bool // x iff available
T // Similar, using (sum) and ×mult
P
next permutation(
RandomAccessIterator last); B idirectionalIterator first, inner product(InputIterator1 first1,
void // as above but using comp B idirectionalIterator last); InputIterator1 last1, Following derived template objects accept two
make heap(RandomAccessIterator InputIterator2
operands. Result obvious by the name.
first, first2,
RandomAccessIterator
bool // as above but using comp
last, T initVal, struct plushTi;
Compare comp);
next permutation(
B idirectionalIterator first, B inaryOperation sum, struct minushTi;
void // sort the [first,last) heap B idirectionalIterator last, B inaryOperation mult); struct multiplieshTi;
sort heap(RandomAccessIterator first, Compare comp); O utputIterator // rk = first
P +k
ei
struct divideshTi;
RandomAccessIterator last); partial sum(InputIterator
i=first
first,
struct modulushTi;
bool // x iff available struct equal tohTi;
void // as above but using comp prev permutation( InputIterator last,
sort heap(RandomAccessIterator
struct not equal tohTi;
first, B idirectionalIterator first, O utputIterator result);
RandomAccessIterator last, B idirectionalIterator last);
struct greaterhTi;
Compare comp); O utputIterator // as above but using binop struct lesshTi;
bool // as above but using comp partial sum( struct greater equalhTi;
prev permutation( InputIterator first, struct less equalhTi;
B idirectionalIterator first, InputIterator last, struct logical andhTi;
B idirectionalIterator last, O utputIterator result, struct logical orhTi;
Compare comp); B inaryOperation binop);

Yotam Medini
c 1998-2009 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
6 STL Quick Reference – Version 1.32 [A4] July 10, 2009

5.1 Function Adaptors templatehclass O perationi In table follows requirements check list for 6.2 Stream Iterators
class binder2nd: public Input, Output and Forward iterators.
unary functionh
5.1.1 Negators Expression; Requirements IOF
O peration::first argument type, might be singular •
O peration::result typei;
X()
templatehclass T,
templatehclass Predicatei class D istance=ptrdiff ti
X u
binder2nd::binder2nd( X(a) ⇒X(a) == a • •
class unary negate : public class istream iterator :
const O peration&
unary functionhPredicate::argument type,
*a=t ⇔ *X(a)=t •
const O peration::second argument type
op,
X u(a) ⇒ u == a • • pubic iteratorhinput iterator tag, T, D istancei;
booli; y);
X u=a
// argument type from unary function u copy of a •
unary negate::unary negate(
O peration::result type // end of stream +7.4
Predicate pred); binder2nd::operator()(
a==b equivalence relation • • istream iterator::istream iterator();
a!=b ⇔!(a==b) • •
bool // negate pred const binder2nd::argument type x);
r = a ⇒ r == a • istream iterator::istream iterator(
binder2ndhO perationi
unary negate::operator()( • • istream& s); +7.4
Predicate::argument type x);
*a convertible to T.
bind2nd(const O peration& op, const T& x); a==b ⇔ *a==*b
unary negatehPredicatei + 7.7. *a=t (for forward, if X mutable) • • istream iterator::istream iterator(
const istream iteratorhT, D istancei&);
not1(const Predicate pred); ++r result is dereferenceable or • • •
5.1.3 Pointers to Functions past-the-end. &r == &++r
templatehclass Predicatei
convertible to const X& • • istream iterator::~istream iterator();
class binary negate : public templatehclass A rg, class Resulti convertible to X& •
class pointer to unary function : r==s⇔ ++r==++s const T& istream iterator::operator*() const ;
binary functionh
Predicate::first argument type, public unary functionhA rg, Resulti; r++ convertible to X& • • •
⇔ {X x=r;++r;return x;} istream iterator& // Read and store T value
Predicate::second argument typei; pointer to unary functionhA rg, Resulti *++r convertible to T • • • istream iterator::operator+ +() const ;
ptr fun(Result(*x)(A rg));
booli; *r++
bool // all end-of-streams are equal
+ 7.7. operator= =(const istream iterator,
template<class A rg1, class A rg2,
binary negate::binary negate(
Predicate pred);
const istream iterator);
class Result> 6.1.2 Bidirectional Iterators
bool // negate pred class pointer to binary function :
binary negate::operator()( public binary functionhA rg1, A rg2, struct bidirectional iterator tag {}
Predicate::first argument type x Resulti; The forward requirements and: templatehclass Ti
Predicate::second argument type class ostream iterator :
pointer to binary functionhA rg1,
A rg2,
y);
--r Convertible to const X&. If ∃ r=++s then public iteratorhoutput iterator tag, void, . . . i;
binary negatehPredicatei Resulti --r refers same as s. &r==&--r.
not2(const Predicate pred); ptr fun(Result(*x)(A rg1, A rg2));
--(++r)==r. (--r == --s ⇒ r==s.
r-- ⇔ {X x=r; --r; return x;}. // If delim 6= 0 add after each write
5.1.2 Binders ostream iterator::ostream iterator(
6 Iterators 6.1.3 Random Access Iterator ostream& s,
const char
* delim=0);
templatehclass O perationi #include <iterator> struct random access iterator tag {}
class binder1st: public The bidirectional requirements and ostream iterator::ostream iterator(
unary functionh 6.1 Iterators Categories (m,n iterator’s distance (integral) value): const ostream iterator s);

O peration::second argument type,


O peration::result typei; Here, we will use: r+=n ⇔ {for (m=n; m-->0; ++r);
for (m=n; m++<0; --r);
ostream iterator& // Assign & write (*o=t)
ostream iterator::operator*() const ;
X iterator type. return r;} //but time = O(1).
binder1st::binder1st(
const O peration&
a, b iterator values. a+n ⇔ n+a ⇔ {X x=a; return a+=n]} ostream iterator&
op, r-=n ⇔ r += -n. ostream iterator::operator=(
const O peration::first argument type
r iterator reference (X& r).
y); t a value type T. a-n ⇔ a+(-n). const ostream iterator s);

// argument type from unary function b-a Returns iterator’s distance value n, such
Imposed by empty struct tags.
O peration::result type that a+n == b. ostream iterator& // No-op
a[n] ⇔ *(a+n). ostream iterator::operator+ +();
binder1st::operator()( 6.1.1 Input, Output, Forward
const binder1st::argument type x); a<b Convertible to bool, < total ordering. ostream iterator& // No-op
struct input iterator tag {}+ 7.8 a<b Convertible to bool, > opposite to <. ostream iterator::operator+ +(int);
binder1sthO perationi struct output iterator tag {} a<=b ⇔ !(a>b).
bind1st(const O peration& op, const T& x); struct forward iterator tag {} a>=b ⇔ !(a<b). + 7.4.

Yotam Medini
c 1998-2009 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
STL Quick Reference – Version 1.32 [A4] July 10, 2009 7

6.3 Typedefs & Adaptors Denote 6.3.3 Insert Iterators 7 Examples


RI = reverse iterator
AI = RandomAccessIterator. templatehclass Containeri
templatehCategory, T, 7.1 Vector
D istance=ptrdiff t, Abbreviate:
class back insert iterator : // safe get
Pointer=T*, Reference= T&i typedef RI<AI, T, public output iterator; int vi(const vector<unsigned>& v, int i)
class iterator { Reference, D istancei self ; { return(i < (int)v.size() ? (int)v[i] : -1);}

Category iterator category; templatehclass Containeri // safe set


// Default constructor ⇒ singular value class front insert iterator :
T value type; self::RI(); void vin(vector<int>& v, unsigned i, int n) {
D istance difference type; public output iterator; int nAdd = i - v.size() + 1;
Pointer pointer; explicit // Adaptor Constructor if (nAdd>0) v.insert(v.end(), nAdd, n);
Reference templatehclass Containeri
else v[i] = n;
reference;} self::RI(AIi); }
class insert iterator :
6.3.1 Traits AI self::base(); // adpatee’s position public output iterator; 7.2 List Splice
templatehIi // so that: &*(RI(i)) == &*(i-1) Reference Here T will denote the Container::value type.
void lShow(ostream& os, const list<int>& l) {
self::operator*(); ostream_iterator<int> osi(os, " ");
class iterator traits { Constructors copy(l.begin(), l.end(), osi); os<<endl;}
I::iterator category self // position to & return base()-1 explicit // ∃ Container::push back(const T&)
iterator category; RI::operator+ +(); back insert iterator::back insert iterator( void lmShow(ostream& os, const char* msg,
I::value type value type;
self& // return old position and move
Container& x); const list<int>& l,
const list<int>& m) {
I::difference type difference type; RI::operator+ +(int); // to base()-1 explicit // ∃ Container::push front(const T&) os << msg << (m.size() ? ":\n" : ": ");
I::pointer pointer; front insert iterator::front insert iterator( lShow(os, l);
I::reference reference;} self // position to & return base()+1 Container& x); if (m.size()) lShow(os, m); } // lmShow
// ∃ Container::insert(const T&)
RI::operator- -();
Pointer specilaizations: + 7.8 list<int>::iterator p(list<int>& l, int val)
self& // return old position and move insert iterator::insert iterator( { return find(l.begin(), l.end(), val);}
templatehTi RI::operator- -(int); // to base()+1 Container x,
class iterator traitshT*i { Container::iterator i); static int prim[] = {2, 3, 5, 7};
static int perf[] = {6, 28, 496};
bool // ⇔ s0.base() == s1.base() Denote
random access iterator tag operator= =(const self& s0, const self& s1); const list<int> lPrimes(prim+0, prim+4);
iterator category ; InsIter = back insert iterator const list<int> lPerfects(perf+0, perf+3);
insFunc = push back list<int> l(lPrimes), m(lPerfects);
T value type; reverse iterator Specific iterMaker = back inserter +7.4
ptrdiff t difference type; lmShow(cout, "primes & perfects", l, m);
or l.splice(l.begin(), m);
T* pointer; self // returned value positioned at base()-n InsIter = front insert iterator lmShow(cout, "splice(l.beg, m)", l, m);
T& reference;} reverse iterator::operator+( insFunc = push front
D istance n) const ;
l = lPrimes; m = lPerfects;
iterMaker = front inserter l.splice(l.begin(), m, p(m, 28));
or lmShow(cout, "splice(l.beg, m, ^28)", l, m);
templatehTi self& // change & return position to base()-n InsIter = insert iterator m.erase(m.begin(), m.end()); // <=>m.clear()
class iterator traitshconst T*i { reverse iterator::operator+ =(D istance n); insFunc = insert l = lPrimes;
random access iterator tag l.splice(p(l, 3), l, p(l, 5));
iterator category ; self // returned value positioned at base()+n lmShow(cout, "5 before 3", l, m);
T value type; reverse iterator::operator-( Member Functions & Operators l = lPrimes;
ptrdiff t difference type; D istance n) const ; InsIter& // calls x.insFunc(val) l.splice(l.begin(), l, p(l, 7), l.end());
const T* pointer; lmShow(cout, "tail to head", l, m);
InsIter::operator=(const T& val); l = lPrimes;
const T& reference;} self& // change & return position to base()+n
reverse iterator::operator- =(D istance n);
InsIter& // return *this l.splice(l.end(), l, l.begin(), p(l, 3));
InsIter::operator*(); lmShow(cout, "head to tail", l, m);
6.3.2 Reverse Iterator
Reference // *(*this + n) InsIter& // no-op, just return *this
InsIter::operator+ +(); 'à
, j) 7→ [j − 1,&i − 1).
Transform [i% reverse iterator::operator[ ](D istance n); InsIter& // no-op, just return *this primes & perfects:
InsIter::operator+ +(int);
D istance // r0.base() - r1.base()
2 3 5 7
templatehIteri Template Function 6 28 496
class reverse iterator : public iteratorh operator-(const self& r0, const self& r1);
InsIter // return InsIterhContaineri(x)
splice(l.beg, m): 6 28 496 2 3 5 7
iterator traitshIteri::iterator category, splice(l.beg, m, ^28):
iterator traitshIteri::value type,
self // n + r.base() iterMaker(Container& x); 28 2 3 5 7
operator-(D istance n, // return insert iteratorhContaineri(x, i)
iterator traitshIteri::difference type,
const self& r); 6 496

insert iteratorhContaineri
5 before 3: 2 5 3 7
iterator traitshIteri::pointer, bool // r0.base() < r1.base() tail to head: 7 2 3 5
iterator traitshIteri::referencei; operator<(const self& r0, const self& r1); inserter(Container& x, Iterator i); head to tail: 3 5 7 2

Yotam Medini
c 1998-2009 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
8 STL Quick Reference – Version 1.32 [A4] July 10, 2009

7.3 Compare Object Sort (-0.809,-0.588) 7.7 Iterator and Binder 7.8 Iterator Traits
(0.309,-0.951)
class ModN { // self-refering int template <class Itr>
public: class Interator : public typename iterator_traits<Itr>::value_type
ModN(unsigned m): _m(m) {} 7.5 Binary Search iterator<input_iterator_tag, int, size_t> { mid(Itr b, Itr e, input_iterator_tag) {
bool operator ()(const unsigned& u0, int _n; cout << "mid(general):\n";
const unsigned& u1) // first 5 Fibonacci public: Itr bm(b); bool next = false;
{return ((u0 % _m) < (u1 % _m));} static int fb5[] = {1, 1, 2, 3, 5}; Interator(int n=0) : _n(n) {} for ( ; b != e; ++b, next = !next) {
private: unsigned _m; for (int n = 0; n <= 6; ++n) { int operator*() const {return _n;} if (next) { ++bm; }
}; // ModN pair<int*,int*> p = Interator& operator++() { }
equal_range(fb5, fb5+5, n); ++_n; return *this; } return *bm;
ostream_iterator<unsigned> oi(cout, " "); cout<< n <<":["<< p.first-fb5 <<’,’ Interator operator++(int) { } // mid<input>
unsigned q[6]; << p.second-fb5 <<") "; Interator t(*this);
for (int n=6, i=n-1; i>=0; n=i--) if (n==3 || n==6) cout << endl; ++_n; return t;} template <class Itr>
q[i] = n*n*n*n; } }; // Interator typename iterator_traits<Itr>::value_type
cout<<"four-powers: "; 'à bool operator==(const Interator& i0, mid(Itr b, Itr e,
copy(q + 0, q + 6, oi); const Interator& i1) random_access_iterator_tag) {
for (unsigned b=10; b<=1000; b *= 10) { 0:[0,0) 1:[0,2) 2:[2,3) 3:[3,4) { return (*i0 == *i1); } cout << "mid(random):\n";
vector<unsigned> sq(q + 0, q + 6); 4:[4,4) 5:[4,5) 6:[5,5) bool operator!=(const Interator& i0, Itr bm = b + (e - b)/2;
sort(sq.begin(), sq.end(), ModN(b)); const Interator& i1) return *bm;
cout<<endl<<"sort mod "<<setw(4)<<b<<": "; 7.6 Transform & Numeric { return !(i0 == i1); } } // mid<random>
copy(sq.begin(), sq.end(), oi);
} cout << endl; template <class T> struct Fermat: public template <class Itr>
class AbsPwr : public unary_function<T, T> { binary_function<int, int, bool> { typename iterator_traits<Itr>::value_type
'à public: Fermat(int p=2) : n(p) {} mid(Itr b, Itr e) {
AbsPwr(T p): _p(p) {} int n; typename
four-powers: 1 16 81 256 625 1296 T operator()(const T& x) const int nPower(int t) const { // t^n iterator_traits<Itr>::iterator_category t;
sort mod 10: 1 81 625 16 256 1296 { return pow(fabs(x), _p); } int i=n, tn=1; mid(b, e, t);
sort mod 100: 1 16 625 256 81 1296 private: T _p; while (i--) tn *= t; } // mid
sort mod 1000: 1 16 81 256 1296 625 }; // AbsPwr return tn; } // nPower
int nRoot(int t) const { template <class Ctr>
template<typename InpIter> float return (int)pow(t +.1, 1./n); } void fillmid(Ctr& ctr) {
7.4 Stream Iterators normNP(InpIter xb, InpIter xe, float p) { int xNyN(int x, int y) const { static int perfects[5] =
vector<float> vf; return(nPower(x)+nPower(y)); } {6, 14, 496, 8128, 33550336},
void unitRoots(int n) { transform(xb, xe, back_inserter(vf), bool operator()(int x, int y) const { *pb = &perfects[0];
cout << "unit " << n << "-roots:" << endl; AbsPwr<float>(p > 0. ? p : 1.)); int zn = xNyN(x, y), z = nRoot(zn); ctr.insert(ctr.end(), pb, pb + 5);
vector<complex<float> > roots; return( (p > 0.) return(zn == nPower(z)); } int m = mid(ctr.begin(), ctr.end());
float arg = 2.*M_PI/(float)n; ? pow(accumulate(vf.begin(), vf.end(), 0.), }; // Fermat cout << "mid=" << m << "\n";
complex<float> r, r1 = polar((float)1., arg); 1./p) } // fillmid
for (r = r1; --n; r *= r1) : *(max_element(vf.begin(), vf.end()))); for (int n=2; n<=Mp; ++n) {
roots.push_back(r); } // normNP Fermat fermat(n); list<int> l; vector<int> v;
copy(roots.begin(), roots.end(), for (int x=1; x<Mx; ++x) { fillmid(l); fillmid(v);
ostream_iterator<complex<float> >(cout, float distNP(const float* x, const float* y, binder1st<Fermat>
"\n")); unsigned n, float p) { fx = bind1st(fermat, x); 'à
} // unitRoots vector<float> diff; Interator iy(x), iyEnd(My);
transform(x, x + n, y, back_inserter(diff), while ((iy = find_if(++iy, iyEnd, fx)) mid(general):
{ofstream o("primes.txt"); o << "2 3 5";} minus<float>()); != iyEnd) { mid=0
ifstream pream("primes.txt"); return normNP(diff.begin(), diff.end(), p); int y = *iy, mid(random):
vector<int> p; } // distNP z = fermat.nRoot(fermat.xNyN(x, y)); mid=0
istream_iterator<int> priter(pream); cout << x << ’^’ << n << " + "
istream_iterator<int> eosi; float x3y4[] = {3., 4., 0.}; << y << ’^’ << n << " = "
copy(priter, eosi, back_inserter(p)); float z12[] = {0., 0., 12.}; << z << ’^’ << n << endl;
for_each(p.begin(), p.end(), unitRoots); float p[] = {1., 2., M_PI, 0.}; if (n>2)
for (int i=0; i<4; ++i) { cout << "Fermat is wrong!" << endl;
'à float d = distNP(x3y4, z12, 3, p[i]); }
cout << "d_{" << p[i] << "}=" << d << endl; }
unit 2-roots:
} }
(-1.000,-0.000)
unit 3-roots: 'à 'à
(-0.500,0.866)
(-0.500,-0.866) d_{1}=19 3^2 + 4^2 = 5^2
unit 5-roots: d_{2}=13 5^2 + 12^2 = 13^2
(0.309,0.951) d_{3.14159}=12.1676 6^2 + 8^2 = 10^2
(-0.809,0.588) d_{0}=12 7^2 + 24^2 = 25^2

Yotam Medini
c 1998-2009 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com

S-ar putea să vă placă și