Buscar

Programação Orientada a Objetos - Poli 2016 - C++ - Aula11 Namespaces, Templates e Biblioteca Padrão

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você viu 3, do total de 61 páginas

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você viu 6, do total de 61 páginas

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você viu 9, do total de 61 páginas

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Prévia do material em texto

Escola Politécnica da Universidade de São Paulo Escola Politécnica da Universidade de São Paulo 
Laboratório de Programação 
Orientada a Objetos para 
Engenharia Elétrica 
Aula 11: Namespaces, Templates e 
Biblioteca Padrão 
PCS3111 
Agenda 
1.  Recapitulação dos principais conceitos OO 
2.  Namespace 
3.  Templates 
4.  STL – Standard Template Library 
5.  Container Vector 
6.  Container List 
7.  Iterators 
2 
Agenda 
1.  Recapitulação dos principais conceitos OO 
2.  Namespace 
3.  Templates 
4.  STL – Standard Template Library 
5.  Container Vector 
6.  Container List 
7.  Iterators 
3 
Principais Conceitos OO 
!  Classe 
•  composta por atributos, métodos 
•  definição (*.h) e implementação (*.cpp) de métodos 
•  objetos são instâncias de classes, podendo ser estáticos 
ou dinâmicos (new e delete) 
!  Hierarquia de classes 
•  herança 
•  reuso 
!  Classe abstrata 
•  só tem definição (*.h) de métodos 
•  implementação de métodos é realizada nas subclasses 
4 
Principais Conceitos OO 
!  Métodos e atributos estáticos 
•  associados à classe e não às instâncias 
•  permitem definir propriedades e comportamentos globais 
!  Sobrecarga de operadores 
•  operadores com mesmo nome e assinaturas diferentes, 
na mesma classe 
!  Polimorfismo 
•  operadores com mesmo nome e assinatura, mas com 
implementações diferentes em classes diferentes 
!  Tratamento de Exceções 
•  permite tratar de modo elegante comportamentos 
anômalos (try e catch) 
5 
Agenda 
1.  Recapitulação dos principais conceitos OO 
2.  Namespace 
3.  Templates 
4.  STL – Standard Template Library 
5.  Container Vector 
6.  Container List 
7.  Iterators 
6 
Namespace 
!  Em certas ocasiões, um programa deve ser dividido 
em múltiplos arquivos. Isto se deve aos seguintes 
fatores: 
•  Uso de bibliotecas de classes 
!  em linguagens procedurais, fornecedores provêm bibliotecas de 
funções; 
!  em linguagens OO, fornecem-se bibliotecas de classes 
•  Organização de vários programadores trabalhando em 
um grande projeto 
!  cada um é responsável por uma funcionalidade 
•  Projeto conceitual de um programa 
7 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Namespace 
8 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
•  Arquivos de Header 
 (*.h) 
•  Diretórios 
•  Projetos 
Namespace 
!  Problema: 
•  Se vários programas (ou partes) forem escritos por 
programadores distintos, muitos nomes comuns de 
funções (ex. add()) e classes (ex. Book) poderiam estar 
repetidos, gerando erros de compilação desses 
programas 
!  Solução: 
1.  Forçar os programadores a escreverem nomes longos 
2.  Criar uma regra de geração de nomes para os 
programadores para que não haja conflitos 
9 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Namespace 
!  Como garantir que programadores distintos não 
usem os mesmos nomes de classes, métodos ? 
•  Programadores preferem nomes curtos: add, subtract, 
find 
•  Deveriam então aumentar estes nomes? 
•  Exemplo: PCS3111_João_Silva_Ex01_alarme.dispara ? 
!  Solução: Namespaces 
•  Um namespace é um nome que se atribui a um pedaço 
de um código fonte 
•  Referência ao código deve ser feita através de uma 
referência ao respectivo namespace 
•  Torna os elementos internos invisíveis ao resto do 
código 
 10 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Namespace 
11 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		#include	<iostream>	
	2			
	3		namespace	geo	{	
	4		const	double	PI	=	3.14159;	
	5		double	circumf	(double	radius)	{	
	6				return	2	*	PI	*	radius;	
	7		}	
	8		}	//end	namespace	geo	
	9			
10		using	namespace	std;	
11		int	main	()	{	
12				double	c1	=	circumf	(10);									//won't	work	here	
13				cout	<<	"c1="	<<	c1	<<	endl;	
14				double	c2	=	geo::circumf	(10);				//OK	
15				cout	<<	"c2="	<<	c2	<<	endl;	
16				using	namespace	geo;	
17				double	c3	=	circumf	(10);									//OK	
18				std::cout	<<	"c3="	<<	c3	<<	std::endl;	
19				return	0;	
20		}	
Aqui usa-se 
a biblioteca 
padrão std 
EX01 
Namespace 
12 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
1		//fileA.h	
2		#	include	<iostream>	
3			
4		namespace	alpha	{	
5		void	funcA()	{	
6				std::cout	<<	"Calling	function	alpha::A"	<<	std::endl;	
7		}	
8		}	
	
1		//fileB.h	
2		#	include	<iostream>	
3			
4		namespace	beta	{	
5		void	funcB()	{	
6				std::cout	<<	"Calling	function	beta::B"	<<	std::endl;	
7		}	
8		}	
	
Em geral, namespaces são definidos em arquivos de header (*.h) 
EX02 
EX02 
Namespace 
13 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Em geral, namespaces são definidos em arquivos de header (*.h) 
	1		//	fileMain.cpp	
	2		#include	<iostream>	
	3		#include	"fileA.h"	
	4		#include	"fileB.h"	
	5		using	namespace	std;	
	6			
	7		int	main	()	{	
	8				alpha::funcA();	
	9				beta::funcB();	
10			
11				using	namespace	alpha;	
12				funcA();	
13				beta::funcB();	
14			
15				using	namespace	beta;	
16				alpha::funcA();	
17				funcB();	
18			
19				return	0;	
20		}	
Saída: 
 
Calling function alpha::A 
Calling function beta::B 
Calling function alpha::A 
Calling function beta::B 
Calling function alpha::A 
Calling function beta::B 
 
EX02 
Namespace 
!  Podem-se criar namespaces sem atribuir um 
nome a eles 
•  São criados automaticamente pelo compilador 
•  É atribuído um nome local, restrito ao arquivo 
•  A visibilidade é restrita a qualquer parte do próprio 
arquivo 
14 
Agenda 
1.  Recapitulação dos principais conceitos OO 
2.  Namespace 
3.  Templates 
4.  STL – Standard Template Library 
5.  Container Vector 
6.  Container List 
7.  Iterators 
15 
Templates 
!  Suponha que desejemos implementar uma função que 
retorna o valor absoluto de um inteiro: 
 
 
!  Se precisarmos para um long: 
!  Se precisarmos para um float: 
 
16 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
int	abs	(int	n)	{											//absolute	value	of	integers	
		return	(n	<	0)	?	-n	:	n;		//if	n	is	negative,	return	-n	
}	
long	abs	(long	n)	{									//absolute	value	of	longs	
		return	(n	<	0)	?	-n	:	n;		//if	n	is	negative,	return	-n	
}	
float	abs	(float	n)	{							//absolute	value	of	floats	
		return	(n	<	0)	?	-n	:	n;		//if	n	is	negative,	return	-n	
}	
Embora as funções sejam distintas, são escritas da mesma forma. 
Daria para escrever uma vez só? Usando Templates!!! 
Templates 
17 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Templates 
18 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		#include	<iostream>	
	2		using	namespace	std;	
	3			
	4		template	<class	T>	//	template	
	5		T	abs	(T	n)	{	
	6				if		(n	<	0)	
	7						return	-n;	
	8				else	
	9						return	n;	
10		}	
11			
12		int	main()	{	
13				int	int1	=	5;	
14				int	int2	=	-6;	
15				long	lon1	=	70000L;	
16				long	lon2	=	-80000L;	
17				double	dub1	=	9.95;	
18				double	dub2	=	-10.15;	
19			
	
	
20				cout	<<	"abs("	<<	int1	<<	")="	
21									<<	abs	(int1)	<<	endl;	
22				cout	<<	"abs("	<<	int2	<<	")="	
23									<<	abs	(int2)	<<	endl;	
24				cout	<<	"abs("	<<	lon1	<<	")="	
25									<<	abs	(lon1)	<<	endl;	
26				cout	<<	"abs("	<<	lon2	<<	")="	
27									<<abs	(lon2)	<<	endl;	
28				cout	<<	"abs("	<<	dub1	<<	")="	
29									<<	abs	(dub1)	<<	endl;	
30				cout	<<	"abs("	<<	dub2	<<	")="	
31									<<	abs	(dub2)	<<	endl;	
32			
33				return	0;	
34		}	
	
	
	
	
	
	
EX03 
Templates 
19 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		#include	<iostream>	
	2		using	namespace	std;	
	3			
	4		template	<class	T>	//	template	
	5		T	abs	(T	n)	{	
	6				if		(n	<	0)	
	7						return	-n;	
	8				else	
	9						return	n;	
10		}	
11			
12		int	main()	{	
13				int	int1	=	5;	
14				int	int2	=	-6;	
15				long	lon1	=	70000L;	
16				long	lon2	=	-80000L;	
17				double	dub1	=	9.95;	
18				double	dub2	=	-10.15;	
19			
	
	
20				cout	<<	"abs("	<<	int1	<<	")="	
21									<<	abs	(int1)	<<	endl;	
22				cout	<<	"abs("	<<	int2	<<	")="	
23									<<	abs	(int2)	<<	endl;	
24				cout	<<	"abs("	<<	lon1	<<	")="	
25									<<	abs	(lon1)	<<	endl;	
26				cout	<<	"abs("	<<	lon2	<<	")="	
27									<<	abs	(lon2)	<<	endl;	
28				cout	<<	"abs("	<<	dub1	<<	")="	
29									<<	abs	(dub1)	<<	endl;	
30				cout	<<	"abs("	<<	dub2	<<	")="	
31									<<	abs	(dub2)	<<	endl;	
32			
33				return	0;	
34		}	
	
	
	
	
	
	
Saída: 
 
abs(5)=5 
abs(-6)=6 
abs(70000)=70000 
abs(-80000)=80000 
abs(9.95)=9.95 
abs(-10.15)=10.15 
 
 
EX03 
Templates 
20 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		#include	<iostream>	
	2		using	namespace	std;	
	3			
	4		template	<class	T>	//function	template	
	5		T	abs	(T	n)	{	
	6				if		(n	<	0)	
	7						return	-n;	
	8				else	
	9						return	n;	
10		}	
11			
12		int	main()	{	
13				int	int1	=	5;	
14				int	int2	=	-6;	
15				long	lon1	=	70000L;	
16				long	lon2	=	-80000L;	
17				double	dub1	=	9.95;	
18				double	dub2	=	-10.15;	
19			
20				cout	<<	"abs("	<<	int1	<<	")="	<<	abs	(int1)	<<	endl;	
21				cout	<<	"abs("	<<	int2	<<	")="	<<	abs	(int2)	<<	endl;	
22				cout	<<	"abs("	<<	lon1	<<	")="	<<	abs	(lon1)	<<	endl;	
23				cout	<<	"abs("	<<	lon2	<<	")="	<<	abs	(lon2)	<<	endl;	
24				cout	<<	"abs("	<<	dub1	<<	")="	<<	abs	(dub1)	<<	endl;	
25				cout	<<	"abs("	<<	dub2	<<	")="	<<	abs	(dub2)	<<	endl;	
26			
27				return	0;	
28		}	
EX03 
Templates 
21 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		#include	<iostream>	
	2		using	namespace	std;	
	3			
	4		template	<class	T>	//function	template	
	5		T	abs	(T	n)	{	
	6				if		(n	<	0)	
	7						return	-n;	
	8				else	
	9						return	n;	
10		}	
11			
12		int	main()	{	
13				int	int1	=	5;	
14				int	int2	=	-6;	
15				long	lon1	=	70000L;	
16				long	lon2	=	-80000L;	
17				double	dub1	=	9.95;	
18				double	dub2	=	-10.15;	
19			
20				cout	<<	"abs("	<<	int1	<<	")="	<<	abs	(int1)	<<	endl;	
21				cout	<<	"abs("	<<	int2	<<	")="	<<	abs	(int2)	<<	endl;	
22				cout	<<	"abs("	<<	lon1	<<	")="	<<	abs	(lon1)	<<	endl;	
23				cout	<<	"abs("	<<	lon2	<<	")="	<<	abs	(lon2)	<<	endl;	
24				cout	<<	"abs("	<<	dub1	<<	")="	<<	abs	(dub1)	<<	endl;	
25				cout	<<	"abs("	<<	dub2	<<	")="	<<	abs	(dub2)	<<	endl;	
26			
27				return	0;	
28		}	
Saída: 
 
abs(5)=5 
abs(-6)=6 
abs(70000)=70000 
abs(-80000)=80000 
abs(9.95)=9.95 
abs(-10.15)=10.15 
 
 
EX03 
Templates 
!  Quando o compilador lê a palavra template no 
código fonte, não gera código pois não sabe 
ainda qual o tipo de argumento 
!  Quando a função é invocada (no exemplo, em 
cout << … abs(lon1) … << “) , o compilador 
sabe que o argumento é do tipo long e neste 
momento instancia o template, isto é, gera o 
código com o tipo correspondente 
!  Isto é repetido para cada vez em que a função é 
invocada. 
22 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Templates 
!  O conceito de templates pode ser estendido 
para classes 
!  Os templates de classes são usados geralmente 
por classes de armazenamento de dados 
(container) 
23 
Templates 
24 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Templates 
25 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		#include	<iostream>	
	2		using	namespace	std;	
	3		const	int	MAX	=	100;						//size	of	array	
	4		template	<class	Type>	class	Stack	{	
	5		private:	
	6				Type	st[MAX];											//stack:	array	of	any	type	
	7				int	top;																//number	of	top	of	stack	
	8		public:	
	9				Stack()	{															//constructor	
10						top	=	-1;	
11				}	
12				void	push	(Type	var)	{		//put	number	on	stack	
13						st[++top]	=	var;	
14				}	
15				Type	pop()	{												//take	number	off	stack	
16						return	st[top--];	
17				}	
18		};	
19			
EX04 
Templates 
26 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
20		int	main()	{	
21				Stack<float>	*s1	=	new	
22				Stack<float>();													//s1	is	object	of	class	Stack	
23				s1->push	(1111.1F);									//push	3	floats,	pop	3	floats	
24				s1->push	(2222.2F);	
25				s1->push	(3333.3F);	
26				cout	<<	"1:	"	<<	s1->pop()	<<	endl;	
27				cout	<<	"2:	"	<<	s1->pop()	<<	endl;	
28				cout	<<	"3:	"	<<	s1->pop()	<<	endl;	
29				Stack<long>	*s2	=	new	
30				Stack<long>();														//s2	is	object	of	class	Stack	
31				s2->push	(123123123L);						//push	3	longs,	pop	3	longs	
32				s2->push	(234234234L);	
33				s2->push	(345345345L);	
34				cout	<<	"1:	"	<<	s2->pop()	<<	endl;	
35				cout	<<	"2:	"	<<	s2->pop()	<<	endl;	
36				cout	<<	"3:	"	<<	s2->pop()	<<	endl;	
37				delete	s1;	
38				delete	s2;	
39				return	0;	
40		}	
EX04 
Templates 
27 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Saída: 
 
1: 3333.3 
2: 2222.2 
3: 1111.1 
1: 345345345 
2: 234234234 
3: 123123123 
 
 
 
20		int	main()	{	
21				Stack<float>	*s1	=	new	
22				Stack<float>();	
23				s1->push	(1111.1F);	
24				s1->push	(2222.2F);	
25				s1->push	(3333.3F);	
26				cout	<<	"1:	"	<<	s1->pop()	<<	endl;	
27				cout	<<	"2:	"	<<	s1->pop()	<<	endl;	
28				cout	<<	"3:	"	<<	s1->pop()	<<	endl;	
29				Stack<long>	*s2	=	new	
30				Stack<long>();	
31				s2->push	(123123123L);	
32				s2->push	(234234234L);	
33				s2->push	(345345345L);	
34				cout	<<	"1:	"	<<	s2->pop()	<<	endl;	
35				cout	<<	"2:	"	<<	s2->pop()	<<	endl;	
36				cout	<<	"3:	"	<<	s2->pop()	<<	endl;	
37				delete	s1;	
38				delete	s2;	
39				return	0;	
40		}	
EX04 
Agenda 
1.  Recapitulação dos principais conceitos OO 
2.  Namespace 
3.  Templates 
4.  STL – Standard Template Library 
5.  Container Vector 
6.  Container List 
7.  Iterators 
28 
STL – Standard Template Library 
!  Biblioteca padrão que fornece classes para 
representar e manipular estruturas de dados 
que usualmente são utilizadas por diversas 
aplicações 
!  Várias entidades, sendo três as principais: 
•  Containers: modos como os dados são organizados 
na memória do computador (ex: pilhas, listas ligadas) 
•  Algoritmos: procedimentos aplicados aos containers 
para processar seus dados (ex: busca, classificação) 
•  Iteradores: generalização de ponteiros, para que se 
refiram a elementos dos containers 
29 
Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
30 
STL – Standard Template Library 
Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
STL – Standard Template Library 
!  Containers 
•  Sequence containers 
!  Vector 
!  List 
!  Deque 
•  Associative containers 
!  Set 
!  Multiset 
!  Map 
!  Multimap 
!  Várias especializaçõesa partir destes containers 
padrão 
 
31 
Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
STL – Standard Template Library 
32 
Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Sequence Containers 
33 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
STL – Standard Template Library 
34 
Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
STL – Standard Template Library 
35 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Agenda 
1.  Recapitulação dos principais conceitos OO 
2.  Namespace 
3.  Templates 
4.  Biblioteca Padrão 
5.  Container Vector 
6.  Container List 
7.  Iterators 
36 
Container Vector 
!  Um Vector é um arranjo (Array) dinâmico de tamanho 
dinâmico, sendo que o programador não precisa se 
preocupar em alocar e desalocar memória 
!  O container expande e contrai o tamanho do vetor à 
medida que dados são inseridos ou retirados do mesmo 
!  Pode usá-lo como um Array, acessando elementos 
através do operador [] ou do operador at. O acesso 
neste modo é muito rápido. 
!  Também se pode adicionar um novo item no final do 
vetor de modo bastante eficiente. Ao realizar esta 
operação, denominada push_back, o tamanho do vetor 
é automaticamente incrementado 
 
37 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Container Vector 
38 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		//	vector.cpp	
	2		//	demonstrates	push_back(),	operator[],	size()	
	3		#include	<iostream>	
	4		#include	<vector>	
	5		using	namespace	std;	
	6			
	7		void	print_vector	(vector	<int>	*v)	{	
	8				cout	<<	"size	of	v=	"	<<	v->size()	<<	endl	<<	"v	=	";	
	9			
10				for	(int	j	=	0;	j	<	v->size();	j++)		//display	vector	contents	
11						cout	<<	v->at	(j)	<<	"	";	
12			
13				cout	<<	endl;	
14		}	
15			
EX05 
Container Vector 
39 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
17		int	main()	{	
18				vector<int>	*v	=	new		vector<int>	();		//create	a	vector	
19				print_vector	(v);	
20				v->push_back	(10);										//put	values	at	end	of	array	
21				v->push_back	(11);	
22				v->push_back	(12);	
23				v->push_back	(13);	
24				print_vector	(v);	
25				v->pop_back();	
26				v->pop_back();	
27				print_vector	(v);	
28				(*v)	[0]	=	20;	
29				v->at	(1)	=	21;	
30				print_vector	(v);	
31				delete	v;	
32				return	0;	
33		}	
EX05 
Container Vector 
40 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
17		int	main()	{	
18				vector<int>	*v	=	new		vector<int>	();		
19				print_vector	(v);	
20				v->push_back	(10);											
21				v->push_back	(11);	
22				v->push_back	(12);	
23				v->push_back	(13);	
24				print_vector	(v);	
25				v->pop_back();	
26				v->pop_back();	
27				print_vector	(v);	
28				(*v)	[0]	=	20;	
29				v->at	(1)	=	21;	
30				print_vector	(v);	
31				delete	v;	
32				return	0;	
33		}	
Saída: 
 
size of v= 0 
v = 
size of v= 4 
v = 10 11 12 13 
size of v= 2 
v = 10 11 
size of v= 2 
v = 20 21 
 
 
EX05 
Agenda 
1.  Recapitulação dos principais conceitos OO 
2.  Namespace 
3.  Templates 
4.  Biblioteca Padrão 
5.  Container Vector 
6.  Container List 
7.  Iterators 
41 
Container List 
!  Um container List é uma lista duplamente ligada, sendo 
que cada elemento tem um ponteiro para o elemento 
anterior e para o elemento seguinte 
!  O container guarda o endereço do início e do final lista, 
e assim o acesso é bastante rápido nas duas direções 
42 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Container List 
43 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		//	list.cpp	
	2		//	demonstrates	push_front(),	front	(),	pop_front	()	
	3		#include	<iostream>	
	4		#	include	<list>	
	5		using	namespace	std;	
	6			
	7		int	main()	{	
	8				list	<int>	*ilist	=	new	list	<int>	();	
	9				ilist->push_back	(30);	
10				ilist->push_back	(40);	
11				ilist->push_front	(20);	
12				ilist->push_front	(10);	
13				int	size	=	ilist->size();	
14			
15				for	(int	j	=	0;	j	<	size;	j++)	{	
16						cout	<<	ilist->front()	<<	"	";	
17						ilist->pop_front();	
18				}	
19			
20				cout	<<	endl;	
21				return	0;	
22		}	
EX06 
Container List 
44 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		//	list.cpp	
	2		//	demonstrates	push_front(),	front	(),	pop_front	
()	
	3		#include	<iostream>	
	4		#	include	<list>	
	5		using	namespace	std;	
	6			
	7		int	main()	{	
	8				list	<int>	*ilist	=	new	list	<int>	();	
	9				ilist->push_back	(30);	
10				ilist->push_back	(40);	
11				ilist->push_front	(20);	
12				ilist->push_front	(10);	
13				int	size	=	ilist->size();	
14			
15				for	(int	j	=	0;	j	<	size;	j++)	{	
16						cout	<<	ilist->front()	<<	"	";	
17						ilist->pop_front();	
18				}	
19			
20				cout	<<	endl;	
21				return	0;	
22		}	
Saída: 
 
10 20 30 40 
EX06 
Adapter Based Containers 
!  Podem-se criar Containers Adapters 
•  Criam containers de propósito especial, cujas interfaces são 
mais simples que as originais 
•  Na STL, são fornecidos 3 containers de propósito especial: 
pilhas, filas e filas de prioridade. 
 
45 
Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Agenda 
1.  Recapitulação dos principais conceitos OO 
2.  Namespace 
3.  Templates 
4.  Biblioteca Padrão 
5.  Container Vector 
6.  Container List 
7.  Iterators 
46 
Iterators 
!  Podem ser considerados como smart pointers 
•  Podem ser incrementados ou decrementados, 
independentemente da forma de armazenamento dos 
dados 
 
 
 
•  O código acima só pode ser usado se os dados 
estiverem armazenados em espaços contíguos de 
memória 
•  Por exemplo, não funcionaria numa lista ligada 
47 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Iterators 
!  Podem também ser vistos também como 
conectores entre containers e algoritmos 
•  Determinam que algoritmos podem ser usados com 
quais containers 
•  Por exemplo, o algoritmo sort () necessita de acesso 
randômico ao container que deseja ordenar, senão 
teria de iterar o container para achar cada elemento 
antes de movê-lo, e isto seria ineficiente 
•  Um outro exemplo seria o algortimo reverse (), que 
necessita de iterar o container nas duas direções, 
senão também seria muito ineficiente 
•  Iterators são uma solução elegante para conectar 
algoritmos a containers 
48 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Iterators 
49 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Iterators 
50 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Mais 
Genérico 
Mais 
Específico 
Iterators 
51 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Iterators 
52 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Iterators 
53 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002.Ed, SAMS. 
Iterators 
54 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
Iterators 
55 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		//	listout.cpp	
	2		//	iterator	for	loop	for	output	
	3		#include	<iostream>	
	4		#	include	<list>	
	5		using	namespace	std;	
	6			
	7		int	main()	{	
	8				int	arr	[]	=	{2,	4,	6,	8};	
	9				list	<int>	*theList	=	new	list	<int>;	
10			
11				for	(int	k	=	0;	k	<	4;	k++)	//	fill	list	with	array	elements	
12						theList->push_back	(arr[k]);	
13			
14				list	<int>::iterator	iter;	//	iterator	
15			
16				for	(iter	=	theList->begin();	iter	!=	theList->end();	
17									iter++)	
18						cout	<<	*iter	<<	"	";	//display	the	list	
19			
20				cout	<<	endl;	
21				return	0;	
22		}	
EX07 
Iterators 
56 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		//	listout.cpp	
	2		//	iterator	for	loop	for	output	
	3		#include	<iostream>	
	4		#	include	<list>	
	5		using	namespace	std;	
	6			
	7		int	main()	{	
	8				int	arr	[]	=	{2,	4,	6,	8};	
	9				list	<int>	*theList	=	new	list	<int>;	
10			
11				for	(int	k	=	0;	k	<	4;	k++)		
12						theList->push_back	(arr[k]);	
13			
14				list	<int>::iterator	iter;	//	iterator	
15			
16				for	(iter	=	theList->begin();	iter	!=	theList->end();	
17									iter++)	
18						cout	<<	*iter	<<	"	";	//display	the	list	
19			
20				cout	<<	endl;	
21				return	0;	
22		}	
Saída: 
 
2 4 6 8 
EX07 
Iterators 
57 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		//	listfill.cpp	
	2		//	uses	iterator	to	fill	list	with	data	
	3		#include	<iostream>	
	4		#include	<list>	
	5		using	namespace	std;	
	6			
	7		int	main()	{	
	8				list	<int>	*theList	=	new	list	<int>	(5);	
	9				list	<int>::iterator	iter;	//	iterator	
10				int	data	=	0;	
11			
12				for	(iter	=	theList->begin();	iter	!=	theList->end();	
13									iter++)	
14						*iter	=	data	+=	2;	
15			
16				for	(iter	=	theList->begin();	iter	!=	theList->end();	
17									iter++)	
18						cout	<<	*iter	<<	"	";	//display	the	list	
19			
20				cout	<<	endl;	
21				return	0;	
22		}	
EX08 
Iterators 
58 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		//	listfill.cpp	
	2		//	uses	iterator	to	fill	list	with	data	
	3		#include	<iostream>	
	4		#include	<list>	
	5		using	namespace	std;	
	6			
	7		int	main()	{	
	8				list	<int>	*theList	=	new	list	<int>	(5);	
	9				list	<int>::iterator	iter;	//	iterator	
10				int	data	=	0;	
11			
12				for	(iter	=	theList->begin();	iter	!=	theList->end();	
13									iter++)	
14						*iter	=	data	+=	2;	
15			
16				for	(iter	=	theList->begin();	iter	!=	theList->end();	
17									iter++)	
18						cout	<<	*iter	<<	"	";	//display	the	list	
19			
20				cout	<<	endl;	
21				return	0;	
22		}	
Saída: 
 
2 4 6 8 10 
EX08 
Iterators 
59 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		//	iterfind.cpp	-	find()	returns	a	list	iterator	
	2		#include	<iostream>	
	3		#include	<algorithm>	
	4		#include	<list>	
	5		using	namespace	std;	
	6			
	7		int	main()	{	
	8				list	<int>	*theList	=	new	list	<int>	(4);	
	9				list	<int>::iterator	iter;	//	iterator	
10				int	data	=	0;	
11				for	(iter	=	theList->begin();	iter	!=	theList->end();	
12									iter++)	
13						*iter	=	data	+=	2;	
14			
15				iter	=	find	(theList->begin(),	theList->end(),	8);	
16				if	(iter	!=	theList->end()	)	
17						cout	<<	"Found	8."	<<	endl;	
18				else	
19						cout	<<	"Did	not	find	8."	<<	endl;	
20			
21				return	0;	
22		}	
EX09 
Iterators 
60 Based on: [Lafore 2002]. Lafore, R. Object-Oriented Programming in C++. 4th. Edition, 2002. Ed, SAMS. 
	1		//	iterfind.cpp	-	find()	returns	a	list	iterator	
	2		#include	<iostream>	
	3		#include	<algorithm>	
	4		#include	<list>	
	5		using	namespace	std;	
	6			
	7		int	main()	{	
	8				list	<int>	*theList	=	new	list	<int>	(4);	
	9				list	<int>::iterator	iter;	//	iterator	
10				int	data	=	0;	
11				for	(iter	=	theList->begin();	iter	!=	theList->end();	
12									iter++)	
13						*iter	=	data	+=	2;	
14			
15				iter	=	find	(theList->begin(),	theList->end(),	8);	
16				if	(iter	!=	theList->end()	)	
17						cout	<<	"Found	8."	<<	endl;	
18				else	
19						cout	<<	"Did	not	find	8."	<<	endl;	
20			
21				return	0;	
22		}	
Saída: 
 
Found 8. 
EX09 
Bibliografia 
!  LAFORE, R. Object-Oriented Programming in C
++. 4th ed., SAMS, 2002 
61

Outros materiais