You are on page 1of 20

mopeco CrAu

L
Notacao do modelo de classes Conceitos basicos MODEL o ecra.01-0/2A
Ob'eto: Ligaco: Notaco do modelo de classes - Conceitos avancados
nomeObjeto:NomeClasse objetol :Classel NomeAssociago
objeto2:Classe2
Associacao ternaria: Visibilidade:
nomeObjeto:NomeClasse NomeAssociago NomeClasse
Classel Classe2
nomeAtributo = valor Associaoo: +operacaoPtiblica
NomeAssociago #operac5oProtegida
Classel Ctasse3 -operacaoPrivada
nomeExtremAssoc1 nomeExtremAssoc2 Classe2 -operagaoPacote

Classe: Classe abstrata e concreta:


Multiplicidade de AssociagOes: Agregaco:
NomeClasse SuperclasseAbstrata
Classe Exatamente urn ClasseMontagem
operacoAbstratal
NomeClasse operacdoConcreta2
Classe Muitos (zero ou mais)
atributo
atributo : TipoDado[multAtr] 0..1 ClassePartel ClasseParte2
atributo : TipoDado[multAtr] = ValorPadro Classe Opcional (zero ou urn) SubclasseConcretal SubclasseConcreta2

operaco operacoConcretal operagaoConcretal


Classe Um ou mais operagaoConcreta2 operagaoConcreta3
operagao (arg1:Nome1, ...) : TipoResultado Composicao:


ClasseMontagem
Heranca mUltipla, disjunta:
Classe de associaoo: Ordenacao, Bag, Seguencia:
Superclassel Superclasse2
{ordered}
Classel Classe2 Classe ClassePartel ClasseParte2

NomeAssoc {bag)
Classe Subclasse
atributo Restricao sobre objetos:

{sequence) Classe
operaco Classe Heranca multipla, sobreposta: ( atribl 0)
atribl
atrib2
Superclasse

Generalizago (heranca): Associacao qualificada: (overlapping) Restricao sobre ligacdes:


Superclasse Classel Classe2 Al
Classel qualificador Classe2
Classel /1\ (subset) Classe2
A2
Subclassel Subclasse2 Subclasse3
Subclassel Subclasse2
Classe derivada: Associacao derivada: Atributo derivado:
Enumeracao:
/NomeAssociago Classe
Pacote: ComentOrio: /NomeClasse Masse') Classe2
enumeration
NomeEnum / atributo

...texto informal... valorEnum1


NomePacote valorEnum2
AfteodeLco- al(iipv(
Notacao do modelo de interact-5es

Diagrama de casos de uso: Diagrama de atividades:


moCFT('.o I i 441(c3
Notacao do modelo de estados
[condica"ol]
Atorl Evento causa transico entre estados: Estados inicial e final:
[condicdo2]

(Estado
l)
Evento (atributos) [condico] / efeito
Est 102
CacD
O
Ator2
C atividade4
Concorrncia dentro de urn objeto: Pontos de entrada e safda:

Relacionamentos de casos de uso:


Catividade5)
V
EstadoComposto

!nick)
NomeDiagEstados)

Estado
S ubestado3) Fim
eventol

atividade6) Subestado4
Atividades em urn estado:

Diagrama de atividades corn raias:


\,evento2
1 Estado
entry 1 efeitol
do / atividade
Ator1 Ator2 Ator3 eventol / efeito2
Estado aninhado: evento2 1 efeito3
(atividadel) exit 1 efeito4
EstadoComposto
eventol
(atividade2
atividade3
41:=1:0 CI= o
Diagrama de seqii6ncia: \ievento3 evento2

ob'etoA objetoB
Diagrama de atividades corn fluxos de objetos:
operl (a,b) I Divisao de controle: Sincronizaco de controte:
(atividadel .Classe alatividade2) EstadoComposto

:Classe evento1
(atividadel) [estado] <atividade2)
evento2

result2
C++ Reference Card 2002 Greg Book

Key C++ Program Structure Control Structures Functions


// my first program in C++ Decision (if-else) In C, functions must be prototyped before the main
#include <iostream.h> if (condition) { function, and defined after the main function. In
switch keyword, reserved int main () statements; C++, functions may, but do not need to be,
Hello! string { } prototyped. C++ functions must be defined before
// comment commented code cout << Hello World!; else if (condition) { the location where they are called from.
close() library function return 0; statements; // function declaration
} type name(arg1, arg2, ...) {
main variable, identifier }
else { statement1;
variable placeholder in syntax // single line comment statements; statement2;
if (exression) - syntax /* multi-line } ...
statement; comment */ if (x == 3) // curly braces not needed }
flag = 1; // when if statement is type return type of the function
else // followed by only one name name by which the function is called
flag = 0; // statement arg1, arg2 parameters to the function
Identifiers Repetition (while) statement statements inside the function
These are ANSI C++ reserved words and cannot be used as variable names. while (expression) { // loop until // example function declaration
statements; // expression is false // return type int
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, } int add(int a, int b) { // parms
default, delete, do, double, dynamic_cast, else, enum, explicit, extern, false, float, Repetition (do-while) int r; // declaration
for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, do { // perform the statements r = a + b; // add nums
protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, statements; // as long as condition return r; // return value
static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, } while (condition); // is true }
typename, union, unsigned, using, virtual, void, volatile, wchar_t Repetition (for) // function call
init - initial value for loop control variable num = add(1,2);
condition - stay in the loop as long as condition Passing Parameters
is true Pass by Value
Data Types Operators increment - change the loop control variable function(int var); // passed by value
Variable Declaration priority/operator/desc/ASSOCIATIVITY for(init; condition; increment) { Variable is passed into the function and can be
special class size sign type name; statements; changed, but changes are not passed back.
special: volatile 1 :: scope LEFT } Pass by Constant Value
class: register, static, extern, auto 2 () parenthesis LEFT Bifurcation (break, continue, goto, exit) function(const int var);
size: long, short, double [ ] brackets LEFT break; // ends a loop Variable is passed into the function but cannot be
sign: signed, unsigned -> pointer reference LEFT continue; // stops executing statements changed.
type: int, float, char (required) . structure member access LEFT // in current iteration of loop cont- Pass by Reference
name: the variable name (required) sizeof returns memory size LEFT // inues executing on next iteration function(int &var); // pass by reference
// example of variable declaration 3 ++ increment RIGHT label: Variable is passed into the function and can be
extern short unsigned char AFlag; decrement RIGHT goto label; // execution continues at changed, changes are passed back.
TYPE SIZE RANGE ~ complement to one (bitwise) RIGHT // label Pass by Constant Reference
char 1 signed -128 to 127 ! unary NOT RIGHT exit(retcode); // exits program function(const int &var);
unsigned 0 to 255 & reference (pointers) RIGHT Selection (switch) Variable cannot be changed in the function.
short 2 signed -32,768 to 32,767 * dereference RIGHT switch (variable) { Passing an Array by Reference
unsigned 0 to 65,535 (type) type casting RIGHT case constant1: // chars, ints Its a waste of memory to pass arrays and
long 4 signed -2,147,483,648 to + - unary less sign RIGHT statements; structures by value, instead pass by reference.
2,147,483,647 4 * multiply LEFT break; // needed to end flow int array[1]; // array declaration
unsigned 0 - 4,294,967,295 / divide LEFT case constant2: ret = aryfunc(&array); // function call
int varies depending on system % modulus LEFT statements; int aryfunc(int *array[1]) {
float 4 3.4E +/- 38 (7 digits) 5 + addition LEFT break; array[0] = 2; // function
double 8 1.7E +/- 308 (15 digits) - subtraction LEFT default: return 2; // declaration
long double 6 << bitwise shift left LEFT statements; // default statements }
10 1.2E +/- 4,932 (19 digits) >> bitwise shift right LEFT } Default Parameter Values
bool 1 true or false 7 < less than LEFT int add(int a, int b=2) {
wchar_t 2 wide characters <= less than or equal LEFT int r;

Console Input/Output
Pointers > greater than LEFT r=a+b; // b is always 2
type *variable; // pointer to variable >= greater than or equal LEFT return (r);
type *func(); // function returns pointer 8 == equal LEFT [See File I/O on reverse for more about streams] }
void * // generic pointer type != not equal LEFT C Style Console I/O
NULL; // null pointer 9 & bitwise AND LEFT stdin standard input stream Overloading Functions
*ptr; // object pointed to by pointer ^ bitwise NOT LEFT stdout standard output stream Functions can have the same name, and same
&obj // address of object | bitwise OR LEFT stderr standard error stream number of parameters as long as the parameters of
Arrays 10 && logical AND LEFT // print to screen with formatting are different types
int arry[n]; // array of size n || logical OR LEFT printf(format, arg1,arg2,...); // takes and returns integers
int arry2d[n][m]; // 2d n x m array 11 ? : conditional RIGHT printf(nums: %d, %f, %c, 1,5.6,C); int divide (int a, int b)
int arry3d[i][j][k]; // 3d i x j x k array 12 = assignment // print to string s { return (a/b); }
Structures += add/assign sprintf(s,format, arg1, arg2,...); // takes and returns floats
struct name { -= subtract/assign sprintf(s,This is string # %i,2); float divide (float a, float b)
type1 element1; *= multiply/assign // read data from keyboard into { return (a/b); }
type2 element2; /= divide/assign // name1,name2,... divide(10,2); // returns 5
... %= modulus/assign scanf(format,&name1,&name2, ...); divide(10,3); // returns 3.33333333
} object_name ; // instance of name >>= bitwise shift right/assign scanf(%d,%f,var1,var2); // read nums Recursion
name variable; // variable of type name <<= bitwise shift left/assign // read from string s Functions can call themselves
variable.element1; // ref. of element &= bitwise AND/assign sscanf(format,&name1,&name2, ...); long factorial (long n) {
variable->element1; // reference of ^= bitwise NOT/assign sscanf(s,%i,%c,var1,var2); if (n > 1)
pointed to structure |= bitwise OR/assign C Style I/O Formatting return (n * factorial (n-1));
13 , comma %d, %i integer else
%c single character return (1);
%f double (float) }
Initialization of Variables %o octal Prototyping
type id; // declaration User Defined DataTypes %p pointer Functions can be prototyped so they can be used
type id,id,id; // multiple declaration typedef existingtype newtypename ;
%u unsigned after being declared in any order
type *id; // pointer declaration %s char string // prototyped functions can be used
typedef unsigned int WORD;
type id = value; // declare with assign %e, %E exponential // anywhere in the program
enum name{val1, val2, ...} obj_name;
type *id = value; // pointer with assign %x, %X hexadecimal #include <iostream.h>
enum days_t {MON,WED,FRI} days;
id = value; // assignment %n number of chars written void odd (int a);
union model_name {
Examples %g, %G same as f for e,E void even (int a);
type1 element1;
// single character in single quotes C++ console I/O int main () { ... }
type2 element2; ...
char c=A; cout<< console out, printing to screen
} object_name ;
// string in double quotes, ptr to string cin>> console in, reading from keyboard
union mytypes_t {
char *str = Hello; cerr<< console error
char c;
clog<< console log
int i = 1022; int i;
cout<<Please enter an integer: ;
Namespaces
float f = 4.0E10; // 4^10 } mytypes;
cin>>i; Namespaces allow global identifiers under a name
int ary[2] = {1,2} // array of ints struct packed { // bit fields
cout<<num1: <<i<<\n<<endl; // simple namespace
const int a = 45; // constant declaration unsigned int flagA:1; // flagA is 1 bit
Control Characters namespace identifier {
struct products { // declaration unsigned int flagB:3; // flagB is 3 bit
\b backspace \f form feed \r return namespace-body;
char name [30]; }
\ apostrophe \n newline \t tab }
float price;
\nnn character #nnn (octal) \ quote // example namespace
} ;
\NN character #NN (hexadecimal) namespace first {int var = 5;}
products apple; // create instance
apple.name = Macintosh; // assignment Preprocessor Directives namespace second {double var = 3.1416;}
#define ID value // replaces ID with int main () {
apple.price = 0.45;
cout << first::var << endl;
products *pApple; // pointer to struct
pApple->name = Granny Smith;
//value for each occurrence in the code
#undef ID // reverse of #define
Character Strings cout << second::var << endl;
#ifdef ID //executes code if ID defined The string Hello is actually composed of 6 return 0;
pApple->price = 0.35; // assignment
#ifndef ID // opposite of #ifdef characters and is stored in memory as follows: }
#if expr // executes if expr is true Char H e l l o \0 using namespace allows for the current nesting
#else // else Index 0 1 2 3 4 5 level to use the appropriate namespace
Exceptions #elif // else if \0 (backslash zero) is the null terminator character using namespace identifier;
try { #endif // ends if block and determines the end of the string. A string is an // example using namespace
// code to be tried... if statements #line number filename array of characters. Arrays in C and C++ start at namespace first {int var = 5;}
statements; // fail, exception is set // #line controls what line number and zero. namespace second {double var = 3.1416;}
// filename appear when a compiler error str = Hello; int main () {
throw exception;
// occurs str[2] = e; // string is now Heelo using namespace second;
}
catch (type exception) { #error msg //reports msg on cmpl. error common <string.h> functions: cout << var << endl;
// code in case of exception #include file // inserts file into code strcat(s1,s2) strchr(s1,c) strcmp(s1,s2) cout << (var*2) << endl;
statements; // during compilation strcpy(s2,s1) strlen(s1) strncpy(s2,s1,n) return 0;
} #pragma //passes parameters to compiler strstr(s1,s2) }
Class Reference File I/O ACSII Chart
#include <fstream.h> // read/write file Dec C har Dec Char Dec Char Dec Char
Class Syntax
class classname {
Inheritance #include <ofstream.h> // write file 0 N UL 64 @ 128 192
#include <ifstream.h> // read file 1 SO H 65 A 129 193
Functions from a class can be inherited and reused
public: File I/O is done from the fstream, ofstream, and
in other classes. Multiple inheritance is possible. 2 ST X 66 B 130 194
classname(parms); // constructor ifstream classes.
~classname(); // destructor class CPoly { //create base polygon class 3 ET X 67 C 131 195
member1; protected:
File Handles 4 EO T 68 D 132 196
member2; int width, height;
A file must have a file handle (pointer to the file) to 5 ENQ 69 E 133 197
public: 6 ACK 70 F 134 198
protected: access the file.
void SetValues(int a, int b) 7 BEL 71 G 135 199
member3; ifstream infile; // create handle called
{ width=a; height=b;}
... // infile to read from a file 8 BS 72 H 136 200
};
private: ofstream outfile; // handle for writing 9 T AB 73 I 137 201
member4; class COutput { // create base output
public: // class
fstream f; // handle for read/write 10 LF 74 J 138 202
} objectname; 11 VT B 75 K 139 203
void Output(int i);
// constructor (initializes variables) Opening Files 12 FF 76 L 140 204
};
classname::classname(parms) { After declaring a file handle, the following syntax 13 CR 77 M 141 205
void COutput::Output (int i) {
} can be used to open the file
// destructor (deletes variables) cout << i << endl; 14 SO 78 N 142 206
void open(const char *fname, ios::mode);
} 15 SI 79 O 143 207
classname::~classname() { fname should be a string, specifying an absolute
} // CRect inherits SetValues from Cpoly
or relative path, including filename. ios:: mode 16 D LE 80 P 144 208
public members are accessible from anywhere // and inherits Output from COutput
can be any number of the following and repeat: 17 D C1 81 Q 145 209
where the class is visible class CRect: public CPoly, public COutput 18 D C2 82 R 146 210
in Open file for reading
protected members are only accessible from { 19 D C3 83 S 147 211
out Open file for writing
members of the same class or of a friend class public: T
ate Initial position: end of file 20 D C4 84 148 212
private members are accessible from members int area(void)
app Every output is appended at the end of file 21 N AK 85 U 149 213
of the same class, members of the derived classes { return (width * height); }
trunc If the file already existed it is erased 22 SYN 86 V 150 214
and a friend class };
binary Binary mode 23 ET B 87 W 151 215
constructors may be overloaded just like any // CTri inherits SetValues from CPoly
ifstream f; // open input file example 24 C AN 88 X 152 216
other function. define two identical constructors class CTri: public CPoly {
f.open(input.txt, ios::in); 25 EM 89 Y 153 217
with difference parameter lists public:
ofstream f; // open for writing in binary Z
Class Example int area(void) 26 SUB 90 154 218
f.open(out.txt, ios::out | ios::binary
class CSquare { // class declaration { return (width * height / 2); } 27 ESC 91 [ 155 219
| ios::app);
public: }; 28 FS 92 \ 156 220
void Init(float h, float w); void main () {
Closing a File 29 GS 93 ] 157 221
float GetArea(); // functions CRect rect; // declare objects
A file can be closed by calling the handles close 30 RS 94 ^ 158 ? 222 ?
private: // available only to CSquare CTri tri;
function 31 US 95 _ 159 223 ?
float h,w; rect.SetValues (2,9);
f.close(); 32 96 ` 160 224
} // implementations of functions tri.SetValues (2,9); 33 ! 97 a 161 225
void CSquare::Init(float hi, float wi){ rect.Output(rect.area());
Writing To a File (Text Mode) 34 98 b 162 226
cout<<tri.area()<<endl; 35 # 99 c 163 227
h = hi; w = wi; The operator << can be used to write to a file. Like
} 36 $ 100 d 164 228
} cout, a stream can be opened to a device. For file
37 % 101 e 165 229
float CSquare::GetArea() { writing, the device is not the console, it is the file. & f
38 102 166 230
return (h*w); cout is replaced with the file handle. 39 103 g 167 231
} ofstream f; // create file handle 40 ( 104 h 168 232
// example declaration and usage Templates f.open(output.txt) // open file 41 ) 105 i 169 ? 233
CSquare theSquare; Templates allow functions and classes to be f <<Hello World\n<<a<<b<<c<<endl; * j
42 106 170 234
theSquare.Init(8,5); reused without overloading them 43 + 107 k 171 235
area = theSquare.GetArea(); template <class id> function; Reading From a File (Text Mode) 44 , 108 l 172 236
// or using a pointer to the class template <typename id> function; The operator >> can be used to read from a file. It 45 - 109 m 173 237
CSquare *theSquare; // ---------- function example --------- works similar to cin. Fields are seperated in the file 46 . 110 n 174 238
theSquare->Init(8,5); template <class T> by spaces. 47 / 111 o 175 239
area = theSquare->GetArea(); ifstream f; // create file handle 0 p ?
T GetMax (T a, T b) { 48 112 176 240
return (a>b?a:b); // return the larger f.open(input.txt); // open file 49 1 113 q 177 241

} while (!f.eof()) // end of file test 2 r
50 114 178 242
Overloading Operators void main () {
int a=9, b=2, c;
f >>a>>b>>c; // read into a,b,c
51 3 115 s 179 243
Like functions, operators can be overloaded. 52 4 116 t 180 244 ?
float x=5.3, y=3.2, z; I/O State Flags
Imagine you have a class that defines a square Flags are set if errors or other conditions occur. 53 5 117 u 181 245 ?
c=GetMax(a,b);
and you create two instances of the class. You can z=GetMax(x,y); The following functions are members of the file 54 6 118 v 182 246
add the two objects together. } object 55 7 119 w 183 247
class CSquare { // declare a class // ----------- class example ----------- handle.bad() returns true if a failure occurs in 56 8 120 x 184 248
public: // functions template <class T> reading or writing 57 9 121 y 185 249 ?
void Init(float h, float w); handle .fail() returns true for same cases as 58 : 122 z 186 250
class CPair {
float GetArea(); bad() plus if formatting errors occur
T x,y; 59 ; 123 { 187 251
CSquare operator + (CSquare); handle.eof() returns true if the end of the file
public: 60 < 124 | 188 252
private: // overload the + operator reached when reading
float h,w;
Pair(T a, T b){ 61 = 125 } 189 253
x=a; y=b; } handle.good() returns false if any of the above 62 > 126 ~ 190 254
} // function implementations
T GetMax(); were true
void CSquare::Init(float hi, float wi){ 63 ? 127 ? 191 255
};
h = hi; w = wi; template <class T> Stream Pointers
} T Pair<T>::GetMax() handle.tellg() returns pointer to current location
float CSquare::GetArea() {
return (h*w);
{ // implementation of GetMax function when reading a file Dynamic Memory
T ret; // return a template handle.tellp() returns pointer to current location
}// implementation of overloaded operator Memory can be allocated and deallocated
ret = x>y?x:y; // return larger when writing a file
CSquare CSquare::operator+ (CSquare cs) { // allocate memory (C++ only)
return ret; // seek a position in reading a file
CSquare temp; // create CSquare object pointer = new type [];
} handle.seekg(position);
temp.h = h + cs.h; // add h and w to int *ptr; // declare a pointer
int main () { handle.seekg(offset, direction);
temp.w = w + cs.w; // temp object ptr = new int; // create a new instance
Pair <int> theMax (80, 45); // seek a position in writing a file
return (temp); ptr = new int [5]; // new array of ints
cout << theMax.GetMax(); handle.seekp(position);
} // deallocate memory (C++ only)
return 0; handle.seekp(offset, direction);
// object declaration and usage delete [] pointer;
} direction can be one of the following
CSquare sqr1, sqr2, sqr3; delete ptr; // delete a single int
ios::beg beginning of the stream
sqr1.Init(3,4); // initialize objects delete [] ptr // delete array
ios::cur current position of the stream pointer
sqr2.Init(2,3); // allocate memory (C or C++)
ios::end end of the stream
void * malloc (nbytes); // nbytes=size
sqr3 = sqr1 + sqr2; // object sqr3 is now
(5,7)
Friend Classes/Functions char *buffer; // declare a buffer
Binary Files
Friend Class Example // allocate 10 bytes to the buffer
buffer is a location to store the characters.
class CSquare; // define CSquare buffer = (char *)malloc(10);
numbytes is the number of bytes to written or read.
class CRectangle { // allocate memory (C or C++)
Advanced Class Syntax int width, height;
write(char *buffer, numbytes);
read(char *buffer, numbytes);
// nelements = number elements
public: // size = size of each element
Static Keyword void convert (CSquare a); void * malloc (nelements, size);
Output Formatting
static variables are the same throughout all }; int *nums; // declare a buffer
streamclass f; // declare file handle
instances of a class. class CSquare { // we want to use the // allocate 5 sets of ints
// set output flags
static int n; // declaration private: // convert function in nums = (char *)calloc(5,sizeof(int));
f.flags(ios_base::flag )
CDummy::n; // reference int side; // the CSquare class, so // reallocate memory (C or C++)
possible flag s
public: // use the friend keyword void * realloc (*ptr, size);
dec fixed hex oct
Virtual Members void set_side (int a) { side=a; } // delete memory (C or C++)
scientific internal left right
Classes may have virtual members. If the function friend class CRectangle; void free (*ptr);
uppercase boolalpha showbase showpoint
is redefined in an inherited class, the parent must };
showpos skipws unitbuf
have the word virtual in front of the function void CRectangle::convert (CSquare a) {
adjustfield left | right | internal
definition width = a.side;
basefield dec | oct | hex ANSI C++ Library Files
height = a.side;
floatfield scientific | fixed The following files are part of the ANSI C++
This keyword }
f.fill() get fill character standard and should work in most compilers.
The this keyword refers to the memory location of // declaration and usage
f.fill(c h) set fill character ch <algorithm.h> <bitset.h> <deque.h>
the current object. CSquare sqr;
f.precision( numdigits) sets the precision for <exception.h> <fstream.h> <functional.h>
int func(this); // passes pointer to CRectangle rect; // convert can be
floating point numbers to numdigits <iomanip.h> <ios.h> <iosfwd.h>
// current object sqr.set_side(4); // used by the
f.put( c ) put a single char into output stream <iostream.h> <istream.h> <iterator.h>
rect.convert(sqr); // rectangle class
f.setf(flag) sets a flag <limits.h> <list.h> <locale.h> <map.h>
Class TypeCasting Friend Functions
f.setf(flag, mask) sets a flag w/value <memory.h> <new.h> <numeric.h>
reinterpret_cast <newtype>(expression); A friend function has the keyword friend in front of
f.width() returns the current number of <ostream.h> <queue.h> <set.h> <sstream.h>
dynamic_cast <newtype>(expression); it. If it is declared inside a class, that function can
characters to be written <stack.h> <stdexcept.h> <streambuf.h>
static_cast <newtype>(expression); be called without reference from an object. An
f.width(num) sets the number of chars to be <string.h> <typeinfo.h> <utility.h>
const_cast <newtype>(expression); object may be passed to it.
written <valarray.h> <vector.h>
/* change can be used anywhere and can
Expression Type have a CRect object passed in */
The type of an expression can be found using // this example defined inside a class
2002 The Book Company Storrs, CT
typeid. typeid returns a type. friend CRect change(CRect); C++ Reference Card
typeid(expression); CRectangle recta, rectb; // declaration C/C++ Syntax, DataTypes, Functions
refcard@gbook.org
Information contained on this card carries no warranty. No liability is assumed by the maker
rectb = change(recta); // usage Classes, I/O Stream Library Functions of this card for accidents or damage resulting from its use.
28-02-2014 C++11-Novidades-Bueno.cpp 1
/**
===============================================================================
Lista com as principais novidades de C++11
Autor: Andr Duarte Bueno.
===============================================================================
Lista com as principais novidades de C++11 -> Ncleo da linguagem
=============================================================================== */
// [ ] ---------------------------------------------------------------------> auto
auto x = 3;

// [ ] ---------------------------------------------------------------------> decltype
decltype(x) y;

// [ ] ---------------------------------------------------------------------> nullptr
char *pc = nullptr; // OK
int *pi = nullptr; // OK

// [ ] ---------------------------------------------------------------------> rvalue reference


template<typename T> void f(T&& param); // parmetro do tipo rvalue reference
template<typename T> void f(std::vector<T>&& param); // parmetro do tipo rvalue reference
int main() { int&& var1 = 10; // rvalue reference
cout << "\nvar1 = " << var1 ; }

// [ ] ---------------------------------------------------------------------> novas strings


char s8[] = u8"UTF-8 cstring. "; // const char[].
char16_t s16[] = u"UTF-16 cstring. "; // const char16_t[].
char32_t s32[] = U"UTF-32 cstring. "; // const char32_t[].
cout << u8"This is a Unicode Character: \u2018" << endl;

// [ ] ---------------------------------------------------------------------> raw strings


// C++11 fornece a opo de raw strings literal: R("string"), no interpretada
cout << "(\a xx \b yy \t zz \n)" << endl;
cout << R"(\a xx \b yy \t zz \n)" << endl;

// [ ] ---------------------------------------------------------------------> sizeof
// C++11 permite obter o sizeof de membro da classe
cout << "sizeof(CPonto) = " << sizeof(CPonto)<< endl;
cout << "sizeof(CPonto::x) = " << sizeof(CPonto::x)<< endl;

// [ ] ---------------------------------------------------------------------> enum class


// A vantagem que a mesma no pode ser convertida para int;
enum class EDiaSemanaCpp11 { segunda = 2, terca = 3, quarta = 4, quinta = 5, sexta = 6 };

// [ ] ---------------------------------------------------------------------> enum class: tipo


// Tambm podemos definir o tipo usado pela enumerao
enum class EMesesAnoCpp11: unsigned int { janeiro = 1, fevereiro, marco, abril,
maio, junho, julho, agosto, setembro, outubro, novembro, dezembro };

// [ ] ---------------------------------------------------------------------> union
union UMiscelanea { bool b; int i; double d;
CPonto p; // C++11 retirou restrio dos tipos aceitos em unies
UMisccelanea() { new( &p ) CPonto(); } };

// [ ] ---------------------------------------------------------------------> static_assert
static_assert (constant-expression, error-message);
static_assert(sizeof(int) <= sizeof(T), "A dimenso de T no suficiente!");
static_assert(std::is_integral<T>::value, "O parmetro de f deve ser do tipo integral.");
static_assert((pi < 3.14) && ( pi > 3.15), "Aumentar preciso de pi!");

// [ ] ---------------------------------------------------------------------> constexpr
constexpr int FuncaoConstante() { return 5; }
constexpr int XY (int x, int y) { return x * y; }
constexpr double aceleracaoGravidade = 9.8;

// [ ] ---------------------------------------------------------------------> range based for


int vetor_estilo_c[5] = { 1, 2, 3, 4, 5 };
for (int &elemento_vetor : vetor_estilo_c) cout << elemento_vetor << endl;
vector<int> v(5);
for( auto elemento_vetor : v ) cout << elemento_vetor << endl;

/home/bueno/Documentos/03-Pesquisa/4-Desenvolvimento/1-Atual/libldsc-docs/C++11-Novidades-Bueno.cpp
28-02-2014 C++11-Novidades-Bueno.cpp 2

// [ ] ---------------------------------------------------------------------> Inicializao
uniforme
int x3{5.0}, x4 ={5.3}; // Com inicializao uniforme de C++11 aponta erro
int x5, x6{}; // x5 valor indefinido, x6 valor padro = 0
int *ptr1,*ptr2{}; // ptr1 valor indefinido, ptr2 em C++11 assume valor nullptr
char cx{14},cy{35000}; // cx OK, 14 do tipo inteiro; cy Erro, estouro do intervalo
std::vector<int> vx { 0, 1, 2, 4, 5 }; // OK
std::vector<int> vy { 1, 2.3, 4, 5.6 }; // Erro
int vc1[3]; // Cria vetor estilo de C, com 3 elementos [0->2], valores indefinidosint
vc2
[]= {1,2,3}; // Cria vetor estilo de C, com 3 elementos [0->2], valores definidos

// [ ] -----------------------------------------------------------------> Lista inicializao


class CLista { private: vector< float > v;
public: CLista( std::initializer_list<float> lista ):v(lista){};
vector< float > V() { return v; }; };

struct SPonto { float x; float y; // Construtor


SPonto(float _x, float _y): x(_x), y(_y) { std::cout << "Passou pelo construtor de SPonto;";}
};
SPonto GetSPonto() { return { 0.0, 0.9 }; } // O objeto criado sem usarmos o tipo SPonto

void Saida ( std::initializer_list<int> l) // Note que recebe como parmetro a lista l.


{ for (auto it = l.begin(); it != l.end(); ++it) std::cout << *it << "\n"; }

int main() { // Chama funo saida, imprime valores na tela


Saida ({0,1,2,3,4,5,6,7,8,9}); // Usando initializer_list
CLista lista{ 5.1, 5.2, 5.3, 5.4 }; // Cria objeto lista
vector<int> v{ 1,2,3,4,5 }; // Usando initializer_list com biblioteca padro

SPonto p2 { 5.1 , 6.1 }; // Usando inicializao uniforme padro C++11


// Criando uma lista de pontos usando inicializao uniforme padro C++11
SPonto lista_pontos[4] = { { 5.2,6.2 }, {5.3,6.3}, {5.4,6.4}, {5.5,6.5} };
}

// [ ] ---------------------------------------------------------------------> Funes lambda


/*auto nomeFuncao = [captura](parametros)->tipoRetorno {corpo da funcao}
[]: No capturar nada.
[=]: Todas as variveis externas so capturadas por valor.
[&]: Todas as variveis externas so capturadas por referncia.
[x, &y]: capturar x por valor(cpia) e y por referncia.
[&, x]: Todas as variveis externas so capturadas por referncia, exceto x que por valor.
[=, &z]: Todas as variveis externas so capturadas por valor, exceto z que por referncia.
*/

// Funo lambda annima criada e j executada


[] { std::cout << "Funo lambda criada e j executada" << std::endl; } ();

// Funo lambda criada e chamada a seguir


auto l = [] { std::cout << "Funo lambda criada e chamada a seguir" << std::endl; };
l(); // Chama funo lambda

// Definio de funo lambda que no captura nada e que no recebe parmetros.


auto ptr_funcao = [] () { cout << "Ol mundo!\n"; };
ptr_funcao();

// Definio de funo lambda que no captura nada e que recebe os parmetros x e y.


auto ptr_funcao2 = [](int x, int y) { return x + y; }
cout << " x + y = " << ptr_funcao2(3,4) << endl;

// Usando funo lambda com captura por referencia


int soma = 0;
auto Soma = [&soma]( int x ) { soma += x; cout << "Soma = " << soma << endl; };
Soma(10);

// [ ] ---------------------------------------------------------------> novo formato funes


auto X(int _x) -> void { x = _x; }
auto X() -> int { return x; }

/home/bueno/Documentos/03-Pesquisa/4-Desenvolvimento/1-Atual/libldsc-docs/C++11-Novidades-Bueno.cpp
28-02-2014 C++11-Novidades-Bueno.cpp 3
auto Set(int _x, int _y) -> void;
auto CPonto::Set(int _x, int _y) -> void{ x = _x; y = _y; }

// [ ] ---------------------------------------------------------------------> Ponteiro Funo


void FC(int x) { cout << "FC x=" << x << endl; } // // Declara e define funo
void (*pFC)(int) = &FC; // ponteiro para funo C++98
typedef void (*PonteiroFuncao)(double); // ponteiro para funo C++98

using PonteiroFuncao = void (*)(double); // ponteiro para funo C++11


std::function<void(int)> pF11 = &F11; // ponteiro para funo C++11
auto autopF11 = &F11; // ponteiro para funo C++11

class C { void F11(int x) { cout << "F11 x=" << x << endl; } };
void (C::*pF03)(int) = &C::F03; // ponteiro para funo C++98
std::function<void (C&, int)> pF11_ref = &C::F11; // funciona como referencia
std::function<void (C*, int)> pF11_ptr = &C::F11; // funciona como ponteiro

// [ ] ----------------------------------------------------------------> delegao construtor


explicit CPonto (int _x, int _y):x(_x),y(_y) {}
CPonto(int xy) : CPonto(xy,xy) {} // um construtor chama o outro

// [ ] ---------------------------------------------------------------------> default e delete


class NonCopyable { public: // Diz para o compilador desabilitar o operator= (no criar)
NonCopyable& operator=(const NonCopyable&) = delete;

// Diz para o compilador desabilitar o construtor de cpia (no criar)


NonCopyable(const NonCopyable&) = delete;

// Diz para o compilador criar o construtor default


NonCopyable() = default; };

// [ ] ---------------------------------------------------------------------> override e final


class CPonto { virtual auto Entrada() -> void;
virtual auto Saida() -> void; };

class CCirculo: public CPonto {


virtual void Entrada() override ; // sobrecreve mtodo virtual da classe base
virtual void Saida() final; }; // ltima atualizao de Saida

// [ ] ---------------------------------------------------------------------> for_each
char s[] = "Ol Mundo!";
for_each( s, s + sizeof(s), [] (char c){ cout << c << endl; });
int vc[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 };
for_each( begin(vc), end(vc), [](int x) { cout << x << ' ';});
int soma = 0;
for_each( begin(vc), end(vc), [&soma] (int x) { soma += x;});

===============================================================================
Lista com as principais novidades de C++11 -> Biblioteca std
===============================================================================
// [ ] ---------------------------------------------------------------------> array
#include <array>
std::array<int, 4> array_4_int { {1,2,3,4} }; // Precisa de duplo {}
array<int, 3> array_3_int = {1, 2, 3}; // Apos = precisa {} simples
array<string, 2> array_2_string = {"a", "b"} ;
sort(array_4_int.begin(), array_4_int.end());
for(auto& ae: array_4_int) cout << ae << ' ';

// [ ] ---------------------------------------------------------------------> unique_ptr
std::unique_ptr<int> ptr_int3( new int(3) ); // Cria ponteiro e objeto
cout << *ptr_int3 << endl; // Usa
unique_ptr<int> ptr_int5 = std::move(ptr_int3); // Transfere propriedade
cout << *ptr_int5 << endl; // Usa
ptr_int5.reset(); // Destre
ptr_int3.reset(); // No faz nada.

// [ ] ---------------------------------------------------------------------> shared_ptr
// Use shared_ptr quando quizer vrios ponteiros apontando para mesmo objeto,

/home/bueno/Documentos/03-Pesquisa/4-Desenvolvimento/1-Atual/libldsc-docs/C++11-Novidades-Bueno.cpp
28-02-2014 C++11-Novidades-Bueno.cpp 4
// somente quando o ltimo for deletado o objeto ser efetivamente deletado.
shared_ptr<int> ptr_int6(new int(6)); // Cria ponteiro e objeto
cout << *ptr_int6 << endl; // Usa
shared_ptr<int> ptr_int7 = ptr_int6; // ptr7 aponta mesmo objeto que ptr6
cout << *ptr_int7 << endl;
ptr_int6.reset(); // No destre e objeto
cout << *ptr_int7 << endl; // Usa
ptr_int7.reset(); // Agora deleta objeto

// [ ] ---------------------------------------------------------------------> weak_ptr
shared_ptr<int> ptr_int8(new int(8));
cout << *ptr_int8 << endl;
weak_ptr<int> wptr_int8 = ptr_int8; // ptr_int8 owns the memory.
{
shared_ptr<int> ptr_int9 = wptr_int8.lock(); // Agora p8 e p9 acessam a mesma memria.
cout << *ptr_int9 << endl;
if( ptr_int9 ) // Sempre verifique se a memria
cout << *ptr_int9 << endl; // Faa algo com ptr_int9
} // ptr_int9 destrudo; ptr_int8 volta a ter a propriedade.
cout << *ptr_int8 << endl;
ptr_int8.reset(); // A memoria deletada.
}

// [ ] ---------------------------------------------------------------------> function
#include <functional>
function<double(double)> fx2 = [](double x) { return x*x;}; // funcao f
function<double(double)> f2x = [](double x) { return 2.0*x;};// funcao g
// Cada vez mais perto da notao matemtica! Agrupando funes, como g(f(x));
std::function<double(double)> gf(function<double(double)> f, function<double(double)> g )
{ return [=](double x) { return g(f(x)); };
// Uso de gf, cria funcao fx4, retorna double, recebe funcao
function<double(double)> fx4 = gf(fx2, fx2);
int main() { double x = 3;
cout << "x = " << x << end;
cout << "fx2 = " << fx2(x) << endl;
cout << "fx4 = " << fx4(x) << endl; }

// [ ] ---------------------------------------------------------------------> bind
// Declara funo f que recebe dois parmetros, um int e uma string
void fis( int x, string s) { cout << "int x = " << x << " string s = " << s << endl; }
int main() {
fis( 2, " oi tudo bem ");
// Cria ponteiro para funo fis que recebe apenas a string
std::function<void( string )> fs = std::bind(&fis, 3 , std::placeholders::_1);
fs("Usando fs, passando apenas a string");
// Cria ponteiro para funo alternativa que recebe apenas o inteiro
function<void( int )> fi = std::bind(&fis, "Usando fi" ,std::placeholders::_2);
fi(7); }

// [ ] ---------------------------------------------------------------------> pair
// Mostra uso de tie com pair<> e equivalencia de pair com tuple
pair<double,double> p = make_pair(1.1,2.2);
cout << "get<0>(p) = " << get<0>(p) << " , get<1>(p) = " << get<1>(p) << endl;
cout << "p.first = " << p.first << " , p.second = " << p.second << endl;

// [ ] ---------------------------------------------------------------------> tuple
// Mostra uso de tuple, get<>, tie, pair
#include <tuple>
// Cria tuple com 3 doubles
tuple<double, double, double> notasJoao(8.7,4.2,5.7);
cout<< "\nJoao\n"
<< "P1: " << get<0>(notasJoao) << ", " // Acesso aos elementos da tuple
<< "P2: " << get<1>(notasJoao) << ", " // usando funcao get<indice>(objeto_tuple)
<< "P3: " << get<2>(notasJoao) << '\n';
std::get<2>(notasJoao) = 6.3; // Nota p3 corrigida, usa referencia.

// Mostra uso da funcao tie() para obter, separadamente, os valores da tuple


double n1,n2,n3;
tie(n1, n2, n3) = notasJoao;

/home/bueno/Documentos/03-Pesquisa/4-Desenvolvimento/1-Atual/libldsc-docs/C++11-Novidades-Bueno.cpp
28-02-2014 C++11-Novidades-Bueno.cpp 5
cout<< "\nJoao\n" << "n1: " << n1 << ", " << "n2: " << n2 << ", " << "n3: " << n3 << '\n';

// [ ] ---------------------------------------------------------------------> forward_as_tuple
// forward_as_tuple cria objeto temporario que funciona como uma tupla
// para objetos rvalue (right value). Note que como sao rvalue, nao alocam espaco em disco;
#include <tuple> // std::tuple e std::make_tuple
// Note que os parametros da tuple sao right value
void print_pack (std::tuple<std::string&&,double&&> pack)
{ std::cout << std::get<0>(pack) << ", " << std::get<1>(pack) << std::endl; }
int main() { print_pack (std::forward_as_tuple(string("Joao"), 8.7)); }

// [ ] --------------------------------------------------------------> all_of any_of none_of


void Teste( vector<int> &v , string msg )
{ cout << "Vetor " << msg << endl;
if ( all_of(v.begin(), v.end(), [](int ev) { return ev > 0;} ) ) // Todos positivos?
cout << "Todos positivos\n";
if ( any_of(v.begin(), v.end(), [](int ev) { return ev > 0;} ) ) // Pelo menos um positivo?
cout << "Pelo menos um positivo\n";
}
int main() { vector<int> v1{ 1, 2, 3, 4, 5}; Teste( v1 , "v1" );
vector<int> v2{ 0,-1, 2, 3, 4, 5}; Teste( v2 , "v2" ); }

// [ ] ---------------------------------------------------------------------> remove_if
bool is_even(int N) { return N % 2 == 0; } // Retorna verdadeiro se for impar
int main() { vector<int> v{1,2,3,4,5,6};
for_each (v.begin(),v.end(),[](int ev){ cout << ev << '\t'; }); // Vetor v antes de
remove_if
remove_if(v.begin(),v.end(),is_even);
for_each (v.begin(),v.end(),[](int ev){ cout << ev << '\t'; }); // Vetor v depois de
remove_if

// Efetivamente remove elementos no intervalo final do vetor


v2.erase(remove_if(v2.begin(), v2.end(), is_even), v2.end()); }

// [ ] ---------------------------------------------------------------------> chrono
#include <chrono> // Biblioteca date time no C++11
#include <ctime> // Biblioteca date time no C
// Cria objeto time_point
chrono::time_point<chrono::system_clock> start;
// Define valor de start como sendo agora (antes do processamento)
start = chrono::system_clock::now();
// Chama funo com determinado tempo de processamento
int result = sin(45);
// Define valor de end como sendo agora (depois do processamento)
auto end = chrono::system_clock::now();
// count() retorna numero ticks, a diferena convertida em segundos.
int elapsed_seconds = chrono::duration_cast<chrono::seconds>(end-start).count();
time_t end_time = chrono::system_clock::to_time_t(end);
cout << "Computao terminada em " << ctime(&end_time)
<< "tempo(s) decorrido : " << elapsed_seconds << "s\n";

// [ ] ---------------------------------------------------------------------> random
// O gerador nmeros randomicos tem duas partes; um motor que gera nmeros randomicos
// e uma distribuio matemtica.
// Motores: linear_congruential_engine,subtract_with_carry_engine e mersenne_twister_enginee.
// Distribuies: uniform_int_distribution, uniform_real_distribution,
// bernoulli_distribution, binomial_distribution, geometric_distribution, poisson_distribution,
// normal_distribution, student_t_distribution, chi_squared_distribution,
// exponential_distribution, gamma_distribution, lognormal_distribution,
// cauchy_distribution, lognormal_distribution, weibull_distribution,
// extreme_value_distribution, fisher_f_distribution, negative_binomial_distribution,
// discrete_distribution, piecewise_constant_distribution, piecewise_linear_distribution.

#include <random>
int main()
{ uniform_int_distribution<int> distribuicao(-20, 20); // Cria distribuio uniforme
mt19937 motor; // Cria motor "Mersenne twister MT19937"
int numeroRandomico = distribuicao(motor); // Gera nmero aleatrio

/home/bueno/Documentos/03-Pesquisa/4-Desenvolvimento/1-Atual/libldsc-docs/C++11-Novidades-Bueno.cpp
28-02-2014 C++11-Novidades-Bueno.cpp 6
std::normal_distribution<double> normal(0.0,1.0); // Normal, media 0 e desvio padrao 1
cout << " media = " << normal.mean() << " desvio padrao = " << normal.stddev()
<< " max = " << normal.max() << " min = " << normal.min() << endl;
normal = normal_distribution<double>(12,3); // Seta media = 12 e desvio padrao = 3

std::default_random_engine motor2; // Cria motor, usa default


auto Normal = std::bind(normal, motor2); // Cria gerador de nmero aleatorio
vector<double> vna(500); // Cria vetor de numeros aleatorios
for( double &v : vna ) v = geradorNormal(); // Gera nmeros aleatros
}

// [ ] ---------------------------------------------------------------------> regex (-lregex)


#include <regex> // regex, replace, match_results
// regex - Classe que representa uma Expresso Regular - ER.
// match_results - representa as ocorrncias, casos em que a ER foi encontrada.
// regex_search - funo usada para localizar uma ocorrncia da ER.
// regex_replace - funo que substitue a ocorrncia encontrada por outro texto.
// As funes regex_search e regex_replace recebem uma expresso regular e uma stringe escrevem
as
// ocorrncias encontradas na estrutura match_results.
int main(){
if (regex_match ("Palmeiras, Campeo Mundial 1951", regex("r") ) )
cout << "\nA expresso regular \"(ras)\" foi encontrada em \"Palmeiras, Campeo Mundial
1951\"";

// A procura pela expressao regular er, sera feita em s pela funcao regex_match.
string s ("Palmeiras campeo mundial"); // string a ser pesquisada
regex er ("r)"); // expressao regular usada na pesquisa
if (regex_match (s,er)) // faz a procura
cout << "\nA expresso regular \"(ras)\" foi encontrada em \"Palmeiras, Campeo Mundial
1951\"";

// Faz a procura usando iteradores


if ( regex_match ( s.begin(), s.end(), er ) ) cout << "range matched\n";

// o mesmo que match_results<const char*> cm;


cmatch cm;
regex_match ("Palmeiras, Campeo Mundial 1951",cm,er);
cout << "string literal with " << cm.size() << " matches\n";

// o mesmo que match_results<string::const_iterator> sm;


smatch sm;
regex_match (s,sm,er);
cout << "string object with " << sm.size() << " matches\n";

regex_match ( s.cbegin(), s.cend(), sm, er);


cout << "Usando intervalo, foram encontradas " << sm.size() << " ocorrncias\n";

// usando os flags de forma explicita:


regex_match ( "subject", cm, er, regex_constants::match_default );
cout << "As ocorrncias so: ";
for (unsigned i=0; i<sm.size(); ++i) { cout << "[" << sm[i] << "] "; }
}
---
#include <regex>
int main(){ std::string fnames[] = {"foo.txt", "bar.txt", "zoidberg"};
std::regex txt_regex("[a-z]+\\.txt");
for (const auto &fname : fnames)
std::cout << fname << ": " << std::regex_match(fname, txt_regex) << '\n';}

// [ ] --------------------------------------------------------------------->

/home/bueno/Documentos/03-Pesquisa/4-Desenvolvimento/1-Atual/libldsc-docs/C++11-Novidades-Bueno.cpp
STL Quick Reference Version 1.33 [A4] August 19, 2011 1

1 Notations 2.2.2 Members & Operators S:iterator S::erase(S::const iterator first, void // move xs [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 xs 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-2011 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
2 STL Quick Reference Version 1.33 [A4] August 19, 2011

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-2011 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
STL Quick Reference Version 1.33 [A4] August 19, 2011 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
remove copy if (InputIterator
bool
equal(InputIterator1
S1 = [first1 , last1 ) and S2 = [first2 , ?) or first,
S2 = [?, last2 ) caller is responsible that first1, void
InputIterator
InputIterator1 replace if (ForwardIterator first,
last,
function will not overflow S2 . last1,
O utputIterator result,
InputIterator2 first2, ForwardIterator last, Predicate
B inaryPredicate binPred); Predicate&
pred);
4.1 Query Algorithms pred,
const T& newVal); All variants of unique template functions
// [first2 , last2 ) v [first1 , last1 )
Function // f not changing [first, last) ForwardIterator1
remove consecutive (binPred-) duplicates. Thus
for each(InputIterator first, O utputIterator // x result2 + #[first, last) usefull after sort (See 4.3).
search(ForwardIterator1 first1,
InputIterator last, replace copy(InputIterator ForwardIterator // [x,last) gets repetitions
ForwardIterator1 last1,
first,
Function InputIterator unique(ForwardIterator first,
ForwardIterator2 first2,
f ); +7.4 last,
O utputIterator result, ForwardIterator last);
InputIterator // first i so i==last or *i==val ForwardIterator2 last2);
ForwardIterator // as above but using binPred
const T& oldVal,
find(InputIterator first, // [first2 , last2 ) vbinPred [first1 , last1 )
unique(ForwardIterator first,
const T& newVal);
InputIterator last, ForwardIterator1
constT val); +7.2 search(ForwardIterator1 O utputIterator // as above but using pred ForwardIterator last,
B inaryPredicate binPred);
first1,
InputIterator // first i so i==last or pred(i) ForwardIterator1 last1, replace copy if (InputIterator first,
find if (InputIterator first, ForwardIterator2 first2, InputIterator last, O utputIterator // x past last copied
InputIterator last, ForwardIterator2 last2, O utputIterator result, unique copy(InputIterator first,
Predicate pred); +7.7 B inaryPredicate binPred); Predicate& pred, InputIterator last,
const T& newVal); O utputIterator result);
ForwardIterator // first duplicate 4.2 Mutating Algorithms
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,
copy(InputIterator InputIterator
ForwardIterator // first binPred-duplicate first1, const T& value); last,
InputIterator O utputIterator result,
adjacent find(ForwardIterator first, last1,
void fill n(ForwardIterator
O utputIterator first2); B inaryPredicate binPred);
ForwardIterator last,
first,
S ize
B inaryPredicate binPred);
n, void
// x last2 (last1 first1 )
B idirectionalIterator2 reverse(B idirectionalIterator first,
const T& value);
void // n = # equal val
B idirectionalIterator last);
count(ForwardIterator first, copy backward( void // by calling gen()
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); O utputIterator result);
void // n calls to gen()
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-2011 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
4 STL Quick Reference Version 1.33 [A4] August 19, 2011

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-2011 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
STL Quick Reference Version 1.33 [A4] August 19, 2011 5

O utputIterator // S1MS2 , xpast end 4.3.5 Min and Max 4.3.7 Lexicographic Order O utputIterator // rk = sk sk1 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-2011 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
6 STL Quick Reference Version 1.33 [A4] August 19, 2011

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 iterators 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 iterators 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-2011 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
STL Quick Reference Version 1.33 [A4] August 19, 2011 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(); // adpatees 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-2011 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
8 STL Quick Reference Version 1.33 [A4] August 19, 2011

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=134545920
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-2011 d http://www.medini.org/stl/stl.html ) yotam.medini@gmail.com
Arquivo: /home/bueno/Dropbox/2-Ensino/ferencia/CGnuplot-Referencia.h Pgina 1 de 2

class Gnuplot
{ public:
static void Terminal (const std::string & type);
//---------------------------------------------------------------------------------Construtores
/// @brief Construtor, seta o estilo do grafico na construcao.
Gnuplot (const std::string & style = "points");
/// @brief Construtor, plota um grafico a partir dde um vector, diretamente na construcao.
Gnuplot (const std::vector < double >&x,const std::string & title = "",const std::string & style =
"points",
const std::string & labelx = "x",const std::string & labely = "y");
/// @brief Construtor, plota um grafico do tipo x_y a partir de vetores, diretamente na construcao.
Gnuplot (const std::vector < double >&x,const std::vector < double >&y,const std::string & title =
"",
const std::string & style = "points",const std::string & labelx = "x",const std::string &
labely = "y");
/// @brief Construtor, plota um grafico de x_y_z a partir de vetores, diretamente na construcao.
Gnuplot (const std::vector < double >&x,const std::vector < double >&y,const std::vector < double
>&z,
const std::string & title = "",const std::string & style = "points",const std::string &
labelx = "x",
const std::string & labely = "y",const std::string & labelz = "z");
/// @brief Destrutor, necessario para deletar arquivos temporarios.
~Gnuplot ();
//--------------------------------------------------------------------------------------------
/// @brief Envia comando para o gnuplot.
Gnuplot & cmd (const std::string & cmdstr);
/// @brief Sobrecarga operador <<, funciona como Comando.
Gnuplot & operator<< (const std::string & cmdstr);
/// @brief Seta estilos de linhas (em alguns casos sao necessarias informacoes adicionais).
/// lines, points, linespoints, impulses, dots, steps, fsteps, histeps,
/// boxes, histograms, filledcurves
Gnuplot & Style (const std::string & stylestr = "points");
/// @brief Ativa suavizacao. Argumentos para interpolacoes e aproximacoes.
/// csplines, bezier, acsplines (para dados com valor > 0), sbezier, unique,
/// frequency (funciona somente com plot_x, plot_xy, plotfile_x,
Gnuplot & Smooth (const std::string & stylestr = "csplines");
/// @brief Escala o tamanho do ponto usado na plotagem.
Gnuplot & PointSize (const double pointsize = 1.0);
/// @brief Ativa/Desativa o grid (padrao = desativado).
Gnuplot & Grid (bool _fgrid = 1);
/// @brief Seta taxa de amostragem das funcoes, ou dos dados de interpolacao.
Gnuplot & Samples (const int samples = 100);
/// @brief Seta densidade de isolinhas para plotagem de funcoes como superficies (para plotagen 3d).
Gnuplot & IsoSamples (const int isolines = 10);
/// @brief Ativa/Desativa remocao de linhas ocultas na plotagem de superficies (para plotagen 3d).
Gnuplot & Hidden3d (bool _fhidden3d = 1);
/// @brief Ativa/Desativa desenho do contorno em superficies (para plotagen 3d).
/// @param base, surface, both.
Gnuplot & Contour (const std::string & position = "base");
/// @brief Ativa/Desativa a visualizacao da superficie (para plotagen 3d).
Gnuplot & Surface (int _fsurface = 1); /// @brief Ativa/Desativa a legenda (a legenda setada por
padrao).
Gnuplot & Legend (const std::string & position = "default");
/// @brief Ativa/Desativa a legenda (a legenda setada por padrao).
Gnuplot & Legend (int _flegend);
/// @brief Ativa/Desativa o titulo da secao do gnuplot.
Gnuplot & Title (const std::string & title = ""); /// @brief Seta o rotulo (nome) do eixo y.
Gnuplot & YLabel (const std::string & label = "y"); /// @brief Seta o rotulo (nome) do eixo x.
Gnuplot & XLabel (const std::string & label = "x");
/// @brief Seta o rotulo (nome) do eixo z.
Gnuplot & ZLabel (const std::string & label = "z");
/// @brief Seta intervalo do eixo x.
Gnuplot & XRange (const int iFrom, const int iTo);
/// @brief Seta intervalo do eixo y.
Gnuplot & YRange (const int iFrom, const int iTo); /// @brief Seta intervalo do eixo z.
Gnuplot & ZRange (const int iFrom, const int iTo);
/// @brief Seta escalonamento automatico do eixo x (default).
Gnuplot & XAutoscale ();
/// @brief Seta escalonamento automatico do eixo y (default).
Gnuplot & YAutoscale ();
/// @brief Seta escalonamento automatico do eixo z (default).
Gnuplot & ZAutoscale ();
Arquivo: /home/bueno/Dropbox/2-Ensino/ferencia/CGnuplot-Referencia.h Pgina 2 de 2

/// @brief Ativa escala logaritma do eixo x (logscale nao e setado por default).
Gnuplot & XLogscale (const double base = 10);
/// @brief Ativa/Desativa escala logaritma do eixo x (logscale nao e setado por default).
Gnuplot & XLogscale (bool _fxlogscale); /// @brief Ativa escala logaritma do eixo y (logscale nao e
setado por default).
Gnuplot & YLogscale (const double base = 10);
/// @brief Ativa/Desativa escala logaritma do eixo y (logscale nao e setado por default).
Gnuplot & YLogscale (bool _fylogscale); /// @brief Ativa escala logaritma do eixo y (logscale nao e
setado por default).
Gnuplot & ZLogscale (const double base = 10); /// @brief Ativa/Desativa escala logaritma do eixo y
(logscale nao e setado por default).
Gnuplot & ZLogscale (bool _fzlogscale);
/// @brief Seta intervalo da palette (autoscale por padrao).
Gnuplot & CBRange (const int iFrom, const int iTo);
//----------------------------------------------------------------------------------
/// @brief Plota dados de um arquivo de disco.
/// @brief Plota dados de um arquivo de disco.
Gnuplot & PlotFile (const std::string & filename,const int column = 1, const std::string & title =
"");
/// @brief Plota dados de um vector.
Gnuplot & PlotVector (const std::vector < double >&x,const std::string & title = "");
/// @brief Plota pares x,y a partir de um arquivo de disco.
Gnuplot & PlotFile (const std::string & filename, const int column_x = 1,
const int column_y = 2, const std::string & title = "");
/// @brief Plota pares x,y a partir de vetores.
Gnuplot & PlotVector (const std::vector < double >&x, const std::vector < double >&y,
const std::string & title = "");
/// @brief Plota pares x,y com barra de erro dy a partir de um arquivo.
Gnuplot & plotfile_xy_err (const std::string & filename,
const int column_x = 1, const int column_y = 2,
const int column_dy =3, const std::string & title = "");
/// @brief Plota pares x,y com barra de erro dy a partir de um arquivo.
Gnuplot & PlotFileXYErrorBar (const std::string & filename,
const int column_x = 1, const int column_y = 2,
const int column_dy = 3, const std::string & title = "");
/// @brief Plota pares x,y com barra de erro dy a partir de vetores.
Gnuplot & PlotVectorXYErrorBar (const std::vector < double >&x, const std::vector < double >&y,
const std::vector < double >&dy, const std::string & title = "");
/// @brief Plota valores de x,y,z a partir de um arquivo de disco.
Gnuplot & PlotFile (const std::string & filename, const int column_x = 1,
const int column_y = 2,const int column_z = 3, const std::string & title = "");
/// @brief Plota valores de x,y,z a partir de vetores.
Gnuplot & PlotVector (const std::vector < double >&x,const std::vector < double >&y,
const std::vector < double >&z,const std::string & title = "");
/// @brief Plota uma equacao da forma y = ax + b, voce fornece os coeficientes a e b.
Gnuplot & PlotSlope (const double a, const double b,const std::string & title = "");
/// @brief Plota uma equacao fornecida como uma std::string y=f(x).
/// Escrever somente a funcao f(x) e nao y= ; /// A variavel independente deve ser x.
/// Exemplo: gnuplot->PlotEquation(CFuncao& obj);
Gnuplot & PlotEquation (const std::string & equation,const std::string & title = "");
/// @brief Plota uma equacao fornecida na forma de uma std::string z=f(x,y).
/// Escrever somente a funcao f(x,y) e nao z=, as vaiaveis independentes sao x e y.
// gnuplot->PlotEquation3d(CPolinomio());
Gnuplot & PlotEquation3d (const std::string & equation,const std::string & title = "");
/// @brief Plota uma imagem.
Gnuplot & PlotImage (const unsigned char *ucPicBuf,const int iWidth, const int iHeight,
const std::string & title = "");
//----------------------------------------------------------------------------------
// Repete o ultimo comando de plotagem, seja plot (2D) ou splot (3D)
// Usado para visualizar plotagens, aps mudar algumas opcoes de plotagem
// ou quando gerando o mesmo grafico para diferentes dispositivos (showonscreen, savetops)
Gnuplot & Replot ();
// Reseta uma sessao do gnuplot (prxima plotagem apaga definicoes previas)
Gnuplot & Reset (); // Reseta uma sessao do gnuplot e seta todas as variaveis para o default
Gnuplot & ResetAll ();
// Verifica se a sessao esta valida
bool is_valid ();
// Verifica se a sessao esta valida
bool IsValid ();
};
typedef Gnuplot CGnuplot;
#endif

You might also like