Referência rápida de C++

00% concluído
Origem: Wikilivros, livros abertos por um mundo aberto.
Esta página precisa ser reciclada (discuta).
Ao melhorá-la, você estará ajudando o Wikilivros.
Este item foi movido da Wikipédia para cá
e ainda precisará de adaptações

Linguagem C++[editar | editar código-fonte]

Preprocessador[editar | editar código-fonte]

// comentário até o final da linha
/* comentário de várias linhas */
#include <stdio.h>        // insere o arquivo cabeçalho padrão
#include "myfile.h"       // insere arquivo do diretório corrente
#define X some text       // substitui X por "some text"
#define F(a,b) a+b        // substitui F(1,2) com 1+2
#define X \
  some text               // continução de linha
#undef X                  // remove definição
#if defined(X)            // compilação condicional (#ifdef X)
#else                     // opcional (#ifndef X  ou #if !defined(X))
#endif                    // necessário após #if, #ifdef

Literais[editar | editar código-fonte]

255, 0377, 0xff           // inteiros (decimal, octal, hex) (int)
2147483647L, 0x7fffffffl  // inteiros de (32-bit) (long) 
123.0, 1.23e2             // números do tipo double (real) 
'a', '\141', '\x61'       // caracter (literal, octal, hex) (char)
'\n', '\\', '\' ', '\"'   // nova linha, barra invertida, aspas, aspas dupla
"string\n"                // série de caracteres terminando com nova linha e \0
"hello" "world"           // conecta as strings(série de caracteres) 
true, false               // constantes boleanas 1 e 0

Declarações[editar | editar código-fonte]

int x;                    // declara x como inteiro com valor indefinido
int x=255;                // declara e inicializa x para 255
short s; long l;          // inteiros usuais de 16 ou 32 bits 
char c='a';               // normalmente caracter de 8 bits 
unsigned char u=255; signed char s=-1;  // char pode ou não possuir sinal
unsigned long x=0xffffffffL;            // short, int, long possuem sinal
float f; double d;        // número real de precisão simples ou dupla (nunca sem sinal)
bool b=true;              // verdadeiro ou falso, pode-se usar int (1 or 0)
int a, b, c;              // declarações múltiplas
int a[10];                // array(série) de 10 inteiros (a[0] até a[9])
int a[]={0,1,2};          // inicializa array(série) (ou a[3]={0,1,2}; )
int a[2][3]={{1,2,3},{4,5,6}};  // array de arrays de inteiros
char s[]="hello";         // string (6 elementos incluindo '\0')
int* p;                   // p é um ponteiro de um inteiro (Endereço de memória) 
char* s="hello";          // s aponta para um array sem nome contendo "hello"
void* p=NULL;             // endereço de memória que representa vazio (NULL é 0)
int& r=x;                 // r é a referência (sinônimo) de int x
enum weekend {SAT,SUN};   // weekend é um novo tipo com valores SAT e SUN
enum weekend day;         // day é variável do tipo weekend
enum weekend {SAT=0,SUN=1};  // representação explícita como int
enum {SAT,SUN} day;       //  enum anônimo
typedef String char*;     // string s; significa char* s;
typedef double point3d[3];// define um double[3]
const int c=3;            // constantes devem ser inicializadas, não devem ser atribuídas
const int* p=a;           // conteúdo de p (elementos de p) são constantes
int* const p=a;           // p (mas não seu conteúdo) é constante
const int* const p=a;     // p e seu conteúdo são constantes
const int& cr=x;          // cr não pode ser utilizado para alterar o valor de x

Classes de armazenamento[editar | editar código-fonte]

int x;                    // automático (a memória existe somente no escopo da função)
static int x;             // vida global, a memória (alocada para x) existe enquanto o programa rodar
extern int x;             // apenas informação (declaração), a variável foi definida em outro lugar

Instruções[editar | editar código-fonte]

x=y;                      // toda expressão é uma instrução
int x;                    // declarações são instruções
;                         // instrução vazia
{                         // um bloco é uma única instrução
  int x;                  // o escopo do bloco vai do começo até o final "}"
  a;                      // em C a declaração precede a instrução
}
if (x) a;                 // se x é verdadeiro (diferente de 0), executa a
else if (y) b;            // se não x e y (opcional)
else c;                   // se não x e não y (opcional)

while (x) a;              // repete 0 ou mais vezes enquanto x é verdadeiro 
for (x; y; z) a;          // equivalente a: x; while(y) {a; z;}
do a; while (x);          // equivalente a: a; while(x) a;

switch (x) {              // x tem que ser int
  case X1: a;             // if x == X1 (X1 deve ser const), salte para cá
  case X2: b;             // else if x == X2, salte para cá
  default: c;             // else salte para cá (optional)
}

break;                    // sai do loop while, do, ou for loop, ou switch
continue;                 // salta para a próxima iteração while, do, ou for loop
return x;                 // retorna x como resposta da função

try { a; }
catch (T t) { b; }        // se a despeja T, então executa b
catch (...) { c; }        // se a despeja outra coisa, então executa c

Funções[editar | editar código-fonte]

int f(int x, int);        // f é uma função recebendo dois valores int e retornando um int
void f();                 // f é um procedimento que não recebe nenhum argumento
void f(int a=0);          // f() é equivalente a f(0)
f();                      // valor padrão de retorno é int
inline f();               // otimizado para velocidade
f() { statements; }       // definição da função (deve ser global)
T operator+(T x, T y);    // a+b (se do tipo T) chama operator+(a, b)
T operator-(T x);         // -a chama a função operator-(a)
T operator++(int);        // pós-incremento ++ ou pós-decremento -- (parâmetro ignorado)
extern "C" {void f();}    // f() foi compilada em C

Os parâmetros e valores de retorno de uma função podem ser de qualquer tipo(int, float, etc). Uma função deve ser declarada ou definida antes de ser utilizada. Ela pode ser declarada primeiro e depois definida. Todo programa consiste de um conjunto de declarações de variáveis globais e um conjunto de definições de funções (possivelmente em diferentes arquivos), uma das funções deve ser:

int main()  { statements... }     //ou
int main(int argc, char* argv[]) { statements... }

argv é um array contendo argc strings que vem da linha de comando. Por convenção, main retorna o valor 0 se tudo correu bem, 1 ou valor maior para erros.

Funções com diferentes argumentos podem receber o mesmo nome (overloading ou sobrecarregamento). Operadores exceto :: . .* ? podem ser sobrecarregados. A ordem de precendência não é afetada. Novos operadores não podem ser criados.

Expressões[editar | editar código-fonte]

Operadores são agrupados por precedência, sendo primeiro o maior. Operadores unários e de atribuição são executados da direita para esquerda. Todos os outros são executados da esquerda para direita. Precendência não afeta a ordem de execução indefinida. Não existe teste de tamanho dos arrays, para ponteiros inválidos, etc.

T::X                      // nome X definido na classe T
N::X                      // nome X definido no namespace N
::X                       // nome global X

t.x                       // membro x da struct ou class t
p->x                      // membro x da struct ou class apontada por p
a[i]                      // i-ésimo elemento da array a
f(x,y)                    // chamada da função f passando os argumentos x e y 
T(x,y)                    // objeto da classe T inicializado com x e y
x++                       // incrementa 1 de x, retorna o valor original de x (postfix)
x--                       // decrementa 1 de x, retorna o valor original de x 
typeid(x)                 // tipo de x
typeid(T)                 // igual a typeid(x) se x é um T
dynamic_cast<T>(x)        // converte x para T, checado em tempo de execução
static_cast<T>(x)         // converte x para T, não checado em tempo de execução
reinterpret_cast<T>(x)    // interpeta os bits de x como se fosse T
const_cast<T>(x)          // converte x para o tipo T mas não const

sizeof x                  // número de bytes usado por x
sizeof(T)                 // número de bytes para representar o tipo T
++x                       // incrementa 1 de x, retorna o valor novo de x (prefix)
--x                       // decrementa 1 de x, retorna o valor  novo de x
~x                        // complemento bit a bit de x
!x                        // verdadeiro se x é 0, senão falso
-x                        // menos unário
+x                        // mais unário (default)
&x                        // endereço de x
*p                        // conteúdo do endereço de p (*&x igual a x)
new T                     // retorna o endereço do novo objeto T alocado 
new T(x, y)               // endereço do novo objeto T alocado inicializado com parâmetros x e y
new T[n]                  // endereço do novo array de n elementos T alocados
delete p                  // destrói e livra o elemento apontado por p
delete[] p                // destrói e livra array de objetos apontados por p
(T) x                     // converte x para T (obsoleto, use .._cast<T>(x))

x * y                     // multiplicação
x / y                     // divisão (integers round toward 0)
x % y                     // módulo (resultado possui o sinal de x)
 
x + y                     // adição, ou &x[y]
x - y                     // subtração, ou número de elementos de  *x para *y

x << y                    // x shifted y bits para esqureda (x * pow(2, y)) 
x >> y                    // x shifted y bits direita (x / pow(2, y))

x < y                     // menor que
x <= y                    // menor ou igual a 
x > y                     // maior que
x >= y                    // maior ou igual a

x == y                    // igualdade
x != y                    // desigualdade

x & y                     // e(and) bit a bit  (3 & 6 é 2)

x ^ y                     // bit a bit ou(or) exclusivo  (3 ^ 6 é 5)

x | y                     // bit a bit ou(or) (3 | 6 é 7)

x && y                    // x "e"  y (executa y se e só se x (diferente de 0))

x || y                    // x "ou"  y (executa y se e só se x é falso)

x = y                     // Atribui y a x, retorna o valor de  x
x += y                    // x = x + y, também -= *= /= <<= >>= &= |= ^=

x ? y : z                 // y se x é verdade (diferente de zero), senão z

throw x                   // despeja exceção, aborta se ela não for capturada

x , y                     // executa x e y, retorna y

Classes[editar | editar código-fonte]

class T {                 // um novo tipo T
private:                  // seção acessível somente para as funções membros da classe T
protected:                // acessível às classes derivadas de T
public:                   // acessível a todos 
  int x;                  // dado membro de T
  void f();               // fução membro de T
  void g() {return;}      // fução membro embutida (inline)
  void h() const;         // a função não altera os dados membros
  int operator+(int y);   // t+y significa t.operator+(y)
  int operator-();        // -t significa t.operator-()
  T(): x(1) {}            // construtor com lista de inicialização 
  T(const T& t): x(t.x) {}  // construtor de cópia
  T& operator=(const T& t) {x=t.x; return *this; }  // operador de inicialização
  ~T();                   // destrutor (rotina de limpeza automática)
  explicit T(int a);      // permite t=T(3) mas não t=3
  operator int() const {return x;}             // Operador de conversão 
  void operator>> (std::ostream& out ) const ; // permite t >> string 
  void operator<< (std::istream& in);          // permite t << string mas não string >> t
  friend void i();        // função global i() possui acesso a parte privada
  friend class U;         // membros de U tem acesso privado a T
  static int y;           // dados que todos os objetos T tem em comum
  static void l();        // código em comum. Pode acessar y mas não x
  class Z {};             // classe interior T::Z
  typedef int V;          // T::V significa int
};
void T::f() {             // código para a função membro f da classe T
  this->x = x;}           // esse é o endereço de si mesmo (significa x=x;)
int T::y = 2;             // inicialização dos membros estáticos (required)
T::l();                   // chamada a membro estático
struct T {                // equivalente a: class T { public:
  virtual void f();       // pode ser redeclarado na classe derivada
  virtual void g()=0; };  // deve ser redeclarado na classe derivada (puramente virtual)
class U: public T {};     // classe derivada U herda todos os membros da classe T
class V: private T {};    // os membros herdados de T tornam-se privados
class W: public T, public U {};  // herança múltipla
class X: public virtual T {};    // classe derivada de X possui T diretamente 
std::istream& operator>> (std::istream& is,  T& t);      // permite string >> t
std::ostream& operator<< (std::ostream& os, const T& t); // permite string << t

Todas as classes possuem um construtor de cópia, operador de inicialização e destrutor, que executam as operações correspondentes de cada dado membro e de cada classe base como mostrado acima. Existe ainda o construtor padrão sem argumentos (é necessário para criar arrays) se a classe não possui construtor. Construtores, atribuidores e destrutores não são herdados.

Classes parametrizadas (templates)[editar | editar código-fonte]

template <class T> T f(T t);        // função f definida para todos os tipos
template <class T> class X {        // classe com construtor do tipo de T
  X(T t); };                        // um construtor
template <class T> X<T>::X(T t) {}  // definição de construtor
X<int> x(3);                        // um objeto do tipo  "X de int"
template <class T, class U=T, int n=0>  // classe parametrizada com classe padrão

Espaços de nome (namespace)[editar | editar código-fonte]

namespace N {class T {};} // Esconde o nome T
N::T t;                   // Usa o T dentro do namespace N
using namespace N;        // faz T visivel sem o uso de N::

C/C++ Biblioteca padrão[editar | editar código-fonte]

Somente as funções mais usadas estão listadas. Os arquivos cabeçalios sem .h estão no namespace std.

STDIO.H, CSTDIO (Input/output)[editar | editar código-fonte]

FILE* f=fopen("filename", "r");  // abre para leitura, NULL (0) caso erro
  // Modo pode ser "w" (escrita) "a" append, "a+" update, "rb" binário
fclose(f);                // fecha o arquivo f
fprintf(f, "x=%d", 3);    // imprime "x=3" outras convenções:
  "%5d %u %-8ld"            // int width 5, unsigned int, long left just.
  "%o %x %X %lx"            // octal, hex, HEX, long hex
  "%f %5.1f"                // float or double: 123.000000, 123.0
  "%e %g"                   // 1.23e2, use either f or g
  "%c %s"                   // char, char*
  "%%"                      // %
sprintf(s, "x=%d", 3);    // imprime em um array de char s
printf("x=%d", 3);        // imprime em stdout (terminal se não redirecionado)
fprintf(stderr, ...       // imprime para saída de erro padrão(não redirecionado)
getc(f);                  // lê um char (como um int int) ou EOF (end of file) de f
ungetc(c, f);             // coloca de volta c em f
flush(f);                 // força o buffer a ser escrito em f
fseek(f, n, SEEK_SET);    // posiciona o arquivo binário f em n
ftell(f);                 // posição de f, -1L se houver erro
rewind(f);                // fseek(f, 0L, SEEK_SET); clearerr(f);
feof(f);                  // f está no final do arquivo?
ferror(f);                // Erro em f?
 perror(s);               // imprime char* s e no erro padrão
clearerr(f);              // limpa o código de erro de f
remove("filename");       // apaga arquivo, retorna 0 se OK
rename("old", "new");     // renomeia arquivo, retorna 0 se OK
f = tmpfile();            // cria arquivo temporário no modo "wb+"
tmpnam(s);                // coloca um nome único em char s[L_tmpnam]

STDLIB.H, CSTDLIB (funções variadas)[editar | editar código-fonte]

atof(s); atol(s); atoi(s);// converte char* para float, long, int
rand(), srand(seed);      // inteiro aleatório de 0 até RAND_MAX, reinicia (reset) rand()
void* p = malloc(n);      // aloca n bytes.  Obsoleto: use new
free(p);                  // libera  memória.  Obsoleto: use delete
exit(n);                  // termina o programa, retornando valor n
system(s);                // executa comando s do OS (depende do sistema)
getenv("PATH");           // variável de ambiente ou 0 (depende do sistema)
abs(n); labs(ln);         // valor absoluto como int, long

STRING.H, CSTRING (funções para char*)[editar | editar código-fonte]

Strings são do tipo char[] com um '\0' no ultimo elemento usado.

strcpy(dst, src);         // copia string. Não verifica o tamanho
strcat(dst, src);         // concatena to dst. Não verifica o tamanho
strcmp(s1, s2);           // compara, <0 se s1<s2, 0 se s1==s2, >0 se s1>s2
strncpy(dst, src, n);     // copia ate n caracteres, também strncat(), strncmp()
strlen(s);                // tamanho de s sem contar com \0
strchr(s,c); strrchr(s,c);// endereço do primeiro/ultimo caractere c em s ou 0
strstr(s, sub);           // endereço do primeiro substring em s ou 0
  // mem... funções são para qualquer tipo (void*), do tamanho de n bytes
memmove(dst, src, n);     // copia n bytes de src para dst
memcmp(s1, s2, n);        // compara n bytes como em strcmp
memchr(s, c, n);          // encontra primeiro byte c em s, retorna endereco ou 0
memset(s, c, n);          // atribui n bytes de s para o valor c

CTYPE.H, CCTYPE (Tipos de caractere)[editar | editar código-fonte]

isalnum(c);                //  c é digito? 
isalpha(c); isdigit(c);    //  c é letra?  digito? 
islower(c); isupper(c);    //  c minuscula?  maiuscula? 
tolower(c); toupper(c);    // converte c para maiuscula/minuscula 

MATH.H, CMATH (Floating point math)[editar | editar código-fonte]

sin(x); cos(x); tan(x);   // funções trigonometricas, x (double) em rad
asin(x); acos(x); atan(x);// inversas
atan2(y, x);              // atan(y/x)
sinh(x); cosh(x); tanh(x);// hyperbolicas
exp(x); log(x); log10(x); // e elevado a x, log base e, log base 10
pow(x, y); sqrt(x);       // x elevado a y, raiz quadrada
ceil(x); floor(x);        // arredondamento para cima ou para baixo(double)
abs(x); fmod(x, y);       // valor absoluto, x módulo y

TIME.H, CTIME (Tempo)[editar | editar código-fonte]

clock()/CLOCKS_PER_SEC;   // tempo em segundos desde que o programa começou
time_t t=time(0);         // tempo absoluto em segundos ou -1 se for desconhecido
tm* p=gmtime(&t);         // 0 se UCT não está disponivel, senão p->tm_X onde X é:
                        sec, min, hour, mday, mon (0-11), year (-1900), wday, yday, isdst
asctime(p);               // "Day Mon dd hh:mm:ss yyyy\n"
asctime(localtime(&t));   // mesmo formato, hora local

ASSERT.H, CASSERT (Auxiliar de depuração)[editar | editar código-fonte]

assert(e);                // se e é falso, imprime mensagem e aborta
#define NDEBUG            // (antes #include <assert.h>), desliga o assert

NEW.H, NEW (Assintente para falta de memória)[editar | editar código-fonte]

set_new_handler(handler);                // muda o comportamento quando acaba a memória
void handler(void) {throw bad_alloc();}  // padrão

IOSTREAM.H, IOSTREAM (Substitui stdio.h)[editar | editar código-fonte]

cin >> x >> y;              // lê x e y (qualquer tipo) de stdin (entrada padrão)
cout << "x=" << 3 << endl;  // escreve uma linha em stdout (saida padrão)
cerr << x << y << flush;    // escreve stderr e espera todos os comandos serem eviados
c = cin.get();              // c = getchar();
cin.get(c);                 // lê char
cin.getline(s, n, '\n');    // lê linha em char s[n] até '\n' (default)
if (cin)                    // bom estado (não EOF)?
                            // para ler/gravar qualquer tipo T:
istream& operator>>(istream& i, T& x) {i >> ...; x=...; return i;}
ostream& operator<<(ostream& o, const T& x) {return o << ...;}

FSTREAM.H, FSTREAM (Leitura/gravação de arquivos, funciona como cin cout)[editar | editar código-fonte]

ifstream f1("filename");  // abre arquivo de texto para leitura
if (f1)                   // testa se aberto e se a entrada é valida
  f1 >> x;                // lê objeto de arquivo
f1.get(s);                // lê char ou linha
f1.getline(s, n);         // lê linha no string s[n]
ofstream f2("filename");  // abre arquivo para escrita
if (f2) f2 << x;          // escreve no arquivo

IOMANIP.H, IOMANIP (Foramatação da saída)[editar | editar código-fonte]

cout << setw(6) << setprecision(2) << setfill('0') << 3.1; // imprime "003.10"

STRING (Cadeia de caracteres de tamanho variado)[editar | editar código-fonte]

string s1, s2="hello";    // cria strings
s1.size(), s2.size();     // número de caracteres: 0, 5
s1 += s2 + " " + "world"; // concatenação
s1 == "hello world"       // comparação, também <, >, !=, etc.
s1[0];                    // 'h'
s1.substr(m, n);          // substring de tamanho n começando em  s1[m]
s1.c_str();               // converte para const char*
getline(cin, s);          // lê linha termiando em '\n'

VECTOR (Array/pilha de tamanho variável com alocação de memória)[editar | editar código-fonte]

vector<int> a(10);        // a[0]..a[9] são int (tamanho padrão é 0)
a.size();                 // número de elementos (10)
a.push_back(3);           // aumenta o tamanho para 11, a[10]=3
a.back()=4;               // a[10]=4;
a.pop_back();             // decrementa o tamanho em 1
a.front();                // a[0];
a[20]=1;                  // Crash: não checa os limites
a.at(20)=1;               // como a[20] mas despeja out_of_range()
for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p)
  *p=0;                             // todos os elementos de  a recebem 0
vector<int> b(a.begin(), a.end());  // b é cópia de a
vector<T> c(n, x);                  // c[0]..c[n-1] inicializa para x
T d[10]; vector<T> e(d, d+10);      // e é inicializado de d


PRINT A VECTOR[editar | editar código-fonte]

int A[] = {1, 4, 2, 8, 5, 7};
const int N = sizeof(A) / sizeof(int);
sort(A, A + N);
copy(A, A + N, ostream_iterator<int>(cout, " "));
// The output is " 1 2 4 5 7 8".

DEQUE (array/pilha/fila)[editar | editar código-fonte]

deque<T> é como vector<T>, mas também suporta:

a.push_front(x);          // coloca x em a[0], empurra os outros elementos
a.pop_front();            // remove a[0], empurra os outros elementos

UTILITY (Pair)[editar | editar código-fonte]

pair<string, int> a("hello", 3);  // estrutura de 2 elementos
a.first;                  // "hello"
a.second;                 // 3
a>b;                      // usa ordem lexicográfica na comparação

MAP (array associativa)[editar | editar código-fonte]

map<string, int> a;       // Mapeia de string para int
a["hello"]=3;             // adiciona ou substitui o elemento a["hello"]
for (map<string, int>::iterator p=a.begin(); p!=a.end(); ++p)
  cout << (*p).first << (*p).second;  // Prints hello, 3
a.size();                 // 1

ALGORITHM (Coleção de 60 algoritmos que atuam sobre iteradores)[editar | editar código-fonte]

min(x, y); max(x, y);     // menor/maior de x, y (qualquer tipo com < definido)
swap(x, y);               // troca os valores das variáveis x e y
sort(a, a+n);             // ordena array a[0]..a[n-1] usando o operador <   
sort(a.begin(), a.end()); // ordena vector ou deque

SET[editar | editar código-fonte]

struct ltstr
{
 bool operator()(const char* s1, const char* s2) const
 {
   return strcmp(s1, s2) < 0;
 }
};

 int main()
 {
 const int N = 6;
 const char* a[N] = {"isomer", "ephemeral", "prosaic", 
                     "nugatory", "artichoke", "serif"};
 const char* b[N] = {"flat", "this", "artichoke",
                      "frigate", "prosaic", "isomer"};

 set<const char*, ltstr> A(a, a + N);
 set<const char*, ltstr> B(b, b + N);
 set<const char*, ltstr> C;

 cout << "Set A: ";
 copy(A.begin(), A.end(), ostream_iterator<const char*>(cout, " "));
 cout << endl;
 cout << "Set B: ";
 copy(B.begin(), B.end(), ostream_iterator<const char*>(cout, " "));   
 cout << endl;

 cout << "Union: ";
 set_union(A.begin(), A.end(), B.begin(), B.end(),
           ostream_iterator<const char*>(cout, " "),
           ltstr());   
 cout << endl;

 cout << "Intersection: ";
 set_intersection(A.begin(), A.end(), B.begin(), B.end(),
                  ostream_iterator<const char*>(cout, " "),
                  ltstr());    
 cout << endl;

 set_difference(A.begin(), A.end(), B.begin(), B.end(),
                inserter(C, C.begin()),
                ltstr());
 cout << "Set C (difference of A and B): ";
 copy(C.begin(), C.end(), ostream_iterator<const char*>(cout, " "));
 cout << endl;
 }

Pequenos códigos[editar | editar código-fonte]

FUNCTIONS POINTERS[editar | editar código-fonte]

Define a Function Pointer[editar | editar código-fonte]

int (*pt2Function)(float, char, char) = NULL;                        // C
int (TMyClass::*pt2Member)(float, char, char) = NULL;                // C++
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;     // C++

Calling Convention[editar | editar código-fonte]

void __cdecl DoIt(float a, char b, char c);                             // Borland and Microsoft
void         DoIt(float a, char b, char c)  __attribute__((cdecl));     // GNU GCC

Assign an address to a Function Pointer[editar | editar código-fonte]

C
int DoIt  (float a, char b, char c){ printf("DoIt\n");   return a+b+c; }	
int DoMore(float a, char b, char c)const{ printf("DoMore\n"); return a-b+c; }
							
pt2Function = DoIt;      // short form						
pt2Function = &DoMore;   // correct assignment using address operator		

C++
class TMyClass									
{										
public:										
  int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
  int DoMore(float a, char b, char c) const					
        { cout << "TMyClass::DoMore" << endl; return a-b+c; };
  /* more of TMyClass */
};
pt2ConstMember = &TMyClass::DoMore; // correct assignment using address operator
pt2Member = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore

Comparing Function Pointers[editar | editar código-fonte]

C
if(pt2Function >0){                           // check if initialized
  if(pt2Function == &DoIt)
     printf("Pointer points to DoIt\n"); }
else
  printf("Pointer not initialized!!\n");
C++
if(pt2ConstMember == &TMyClass::DoMore)
   cout << "Pointer points to TMyClass::DoMore" << endl;

Calling a Function using a Function Pointer[editar | editar código-fonte]

C
int result1 = pt2Function    (12, 'a', 'b');          // C short way
int result2 = (*pt2Function) (12, 'a', 'b');          // C 
C++
TMyClass instance1;
int result3 = (instance1.*pt2Member)(12, 'a', 'b');   // C++
int result4 = (*this.*pt2Member)(12, 'a', 'b');       // C++ if this-pointer can be used

TMyClass* instance2 = new TMyClass;
int result4 = (instance2->*pt2Member)(12, 'a', 'b');  // C++, instance2 is a pointer
delete instance2;

How to Pass a Function Pointer as an Argument?[editar | editar código-fonte]

// <pt2Func> is a pointer to a function which returns an int and takes a float and two char
void PassPtr(int (*pt2Func)(float, char, char))
{
  int result = (*pt2Func)(12, 'a', 'b');     // call using function pointer
  cout << result << endl;
}

// execute example code - 'DoIt' is a suitable function like defined above in 2.1-4
void Pass_A_Function_Pointer()
{
   cout << endl << "Executing 'Pass_A_Function_Pointer'" << endl;
   PassPtr(&DoIt);
}

How to Return a Function Pointer ?[editar | editar código-fonte]

Direct solution

// Function takes a char and returns a pointer to a
// function which is taking two floats and returns a float. <opCode>
// specifies which function to return
float (*GetPtr1(const char opCode))(float, float)
{
   if(opCode == '+')
      return &Plus;
   else
      return &Minus; // default if invalid operator was passed
}

Solution using a typedef

// Solution using a typedef: Define a pointer to a function which is taking
// two floats and returns a float
typedef float(*pt2Func)(float, float); 

// Function takes a char and returns a function pointer which is defined
// with the typedef above. <opCode> specifies which function to return
pt2Func GetPtr2(const char opCode)
{
   if(opCode == '+')
      return &Plus;
   else
      return &Minus; // default if invalid operator was passed
}

Execute example code

void Return_A_Function_Pointer()
{
   cout << endl << "Executing 'Return_A_Function_Pointer'" << endl; 
 
   // define a function pointer and initialize it to NULL
   float (*pt2Function)(float, float) = NULL; 

   pt2Function=GetPtr1('+');   // get function pointer from function 'GetPtr1'
   cout << (*pt2Function)(2, 4) << endl;   // call function using the pointer


   pt2Function=GetPtr2('-');   // get function pointer from function 'GetPtr2'
   cout << (*pt2Function)(2, 4) << endl;   // call function using the pointer
}

How to Use Arrays of Function Pointers ?[editar | editar código-fonte]

C

// type-definition: 'pt2Function' now can be used as type
typedef int (*pt2Function)(float, char, char);

// illustrate how to work with an array of function pointers
void Array_Of_Function_Pointers()
{
   printf("\nExecuting 'Array_Of_Function_Pointers'\n"); 
 
   // define arrays and ini each element to NULL, <funcArr1> and <funcArr2> are arrays
   // with 10 pointers to functions which return an int and take a float and two char 

   // first way using the typedef
   pt2Function funcArr1[10] = {NULL};

   // 2nd way directly defining the array
   int (*funcArr2[10])(float, char, char) = {NULL};


   // assign the function's address - 'DoIt' and 'DoMore' are suitable functions
   // like defined above in 2.1-4
   funcArr1[0] = funcArr2[1] = &DoIt;
   funcArr1[1] = funcArr2[0] = &DoMore; 

   /* more assignments */

   // calling a function using an index to address the function pointer
   printf("%d\n", funcArr1[1](12, 'a', 'b'));         //  short form
   printf("%d\n", (*funcArr1[0])(12, 'a', 'b'));      // "correct" way of calling
   printf("%d\n", (*funcArr2[1])(56, 'a', 'b'));
   printf("%d\n", (*funcArr2[0])(34, 'a', 'b'));
}
 

C++

// type-definition: 'pt2Member' now can be used as type
typedef int (TMyClass::*pt2Member)(float, char, char);

// illustrate how to work with an array of member function pointers
void Array_Of_Member_Function_Pointers()
{
   cout << endl << "Executing 'Array_Of_Member_Function_Pointers'" << endl; 

   // define arrays and ini each element to NULL, <funcArr1> and <funcArr2> are
   // arrays with 10 pointers to member functions which return an int and take
   // a float and two char

   // first way using the typedef
   pt2Member funcArr1[10] = {NULL};

   // 2nd way of directly defining the array
   int (TMyClass::*funcArr2[10])(float, char, char) = {NULL};

   // assign the function's address - 'DoIt' and 'DoMore' are suitable member
   //  functions of class TMyClass like defined above in 2.1-4
   funcArr1[0] = funcArr2nd use an array of function pointers in C and C++. The first way uses a      typedef, the second way directly defines the array. It's up to you which way you prefer.

[1] = &TMyClass::DoIt;
   funcArr1[1] = funcArr2[0] = &TMyClass::DoMore;
   /* more assignments */

   // calling a function using an index to address the member function pointer
   // note: an instance of TMyClass is needed to call the member functions
   TMyClass instance;
   cout << (instance.*funcArr1[1])(12, 'a', 'b') << endl;
   cout << (instance.*funcArr1[0])(12, 'a', 'b') << endl;
   cout << (instance.*funcArr2[1])(34, 'a', 'b') << endl;
   cout << (instance.*funcArr2[0])(89, 'a', 'b') << endl;
}

SINGLETON[editar | editar código-fonte]

//: C10:Singleton.cpp
// Static member of same type, ensures that
// only one object of this type exists.
// Also referred to as the "singleton" pattern.
#include <iostream>
using namespace std;
 
class Egg {
  static Egg e;
  int i;
  Egg(int ii) : i(ii) {}
  Egg(const Egg&); // Prevent copy-construction
public:
  static Egg* instance() { return &e; }
  int val() const { return i; }
};

Egg Egg::e(47);

int main() {
  //!  Egg x(1); // Error—can't create an Egg
  // You can access the single instance:
  cout << Egg::instance()->val() << endl;
} ///:~

SINGLETON TEMPLATE[editar | editar código-fonte]

#pragma	once

#ifndef	SINGLETON_H
#define	SINGLETON_H

template <typename T>
class Singleton
{
private:
	Singleton();
	~Singleton();
	const Singleton& operator=(const Singleton&	src);

protected:

public:
	static T* instance()
	{
		T* pTmp	= NULL;
		try
		{
			static T tVar;
			pTmp = &tVar;
		}
		catch(...)
		{
	 		_ASSERT(FALSE);
			pTmp = NULL;
		}
		return pTmp;
	}
};

/*
teste...
typedef Singleton<int> My_singleton;
*/

#endif //SINGLETON_H

READING A TEXT FILE[editar | editar código-fonte]

#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>

int main () {
  char buffer[256];
  ifstream examplefile ("example.txt");
  if (! examplefile.is_open())
  { cout << "Error opening file"; exit (1); } 

  while (! examplefile.eof() )
  {
    examplefile.getline (buffer,100);
    cout << buffer << endl;
  }
  return 0;
}

SPLIT STRING INTO A STRING LIST[editar | editar código-fonte]

#include <fstream>  
#include <iostream>  
#include <vector>
#include <sstream>
#include <string>

void split(const string &in,const char spliter,vector<string> &out)
{
  out.clear();
  vector<size_t> indices; 

  indices.push_back(0);
  //find spliters
  for (size_t i=0;i<in.length();++i)
  {
    if (in[i]==spliter)
      indices.push_back(i+1);
  }
  indices.push_back(in.length());
  
  string tmp;
  for (size_t i=0;i<indices.size()-1;++i)
  {
    out.push_back(string(in, indices[i], indices[i+1] - indices[i]));
  }
}

WRITING A TEXT FILE[editar | editar código-fonte]

#include <fstream.h>

int main () {
  ofstream examplefile ("example.txt");
  if (examplefile.is_open())
  {
    examplefile << "This is a line.\n";
    examplefile << "This is another line.\n";
    examplefile.close();
  }
  return 0;
} 

OBTAINING FILE SIZE[editar | editar código-fonte]

#include <iostream.h>
#include <fstream.h> 

const char * filename = "example.txt";

int main () {
  long l,m;
  ifstream file (filename, ios::in|ios::binary);
  l = file.tellg();
  file.seekg (0, ios::end);
  m = file.tellg();
  file.close();
  cout << "size of " << filename;
  cout << " is " << (m-l) << " bytes.\n";
  return 0;
} 


READING BINARY FILE[editar | editar código-fonte]

#include <iostream.h>
#include <fstream.h>

const char * filename = "example.txt"; 

int main () {
  char * buffer;
  long size;
  ifstream file (filename, ios::in|ios::binary|ios::ate);
  size = file.tellg();
  file.seekg (0, ios::beg);
  buffer = new char [size];
  file.read (buffer, size);
  file.close(); 

  cout << "the complete file is in a buffer"; 

  delete[] buffer;
  return 0;
}

WRITING BINARY FILE[editar | editar código-fonte]

#include <iostream.h>
#include <fstream.h>

const char * filename = "example.txt"; 

int main () 
{
   const char * data = get_buffer();
   long len = get_buffer_size();
   ofstream outfile (filename,ios::out|ios::binary);

   if (outfile.is_open())
   {
     outfile.write(data,len);
     outfile.close();
   }
}

ARVORE BINÁRIA[editar | editar código-fonte]

typedef struct celula *arvore;             
struct celula {
  arvore pai;
  int    chave;
  arvore esq;
  arvore dir;
} ;

// Recebe a raiz r de uma árvore binária.
// Imprime as chaves das celulas em ordem e-r-d.
// endorder

void erd (arvore r) {
    if (r != NULL) {
       erd (r->esq);
       printf ("%d\n", r->chave);
       erd (r->dir); 
    }
}

// endorder
//linear
    while (1) {
       while (r != NULL) {
          p[t++] = r;
          r = r->esq;
       }
       if (t == 0) break;
       r = p[--t];
       printf ("%d\n", r->chave);
       r = r->dir;
    }

// Recebe o endereço r de uma árvore binária não vazia.
// Devolve o endereço da primeira célula na ordem e-r-d. 

arvore primeira (arvore r) {  
    while (r->esq != NULL) 
       r = r->esq;
    return r;
}

// Recebe o endereço de uma célula x. Devolve o endereço 
// da célula seguinte na ordem e-r-d. 

arvore seguinte (arvore x) {  
    if (x->dir != NULL) {
       arvore y = x->dir; 
       while (y->esq != NULL) y = y->esq;
       return y;                                 // *
    }
    while (x->pai != NULL && x->pai->dir == x)   // ** 
       x = x->pai;                               // **
    return x->pai;
}

// Devolve a altura da árvore binária cuja raiz é r.
int altura (arvore r) {
   if (r == NULL) 
      return -1; // altura de árvore vazia é -1
   else {
      int he = altura (r->esq);
      int hd = altura (r->dir);
      if (he < hd) return hd + 1;
      else return he + 1;
   }
}

CONVERTING BETWEEN BIG AND LITLE ENDIAN word 16 bits and Dword 32 bits[editar | editar código-fonte]

#define FlipWord(w) ( (w)<<8 | (w)>>8 )
#define FlipDword(d) ((d)<<24 | (((d)<<8) & 0xFF00) | (((d)>>8) & 0xFF0000) | (d)>>24)

CREATE A RAW FILE TO PHOTOSHOP READ[editar | editar código-fonte]

std::fstream myFile( filename , std::ios::out | std::ios::binary | std::ios::trunc);

char r,g,b,v;
int maxfreq=getMaxFrequence();

for (int j=0;j<_bmpres ;++j)
  for (int i=0;i<_bmpres ;++i){
    v=255-(255 * _bitmap[j][i])/ maxfreq ;
    r=char(gsFloat(255)*(color_copper[3*v]));
    g=char(gsFloat(255)*(color_copper[3*v+1]));
    b=char(gsFloat(255)*(color_copper[3*v+2]));
    myFile <<  r << g << b ;
    }

myFile.close();

DEFINE PARA GERAR RANDOM ENTRE UMA FAIXA[editar | editar código-fonte]

#define getrandom(min, max) \
    ((rand()%(int)(((max) + 1)-(min)))+ (min))

PROCESSANDO LINHA DE COMANDO[editar | editar código-fonte]

#include < stdio.h>
#include < stdlib.h>
void get_args(int argc, char** argv, int* a_value, float* b_value)
{
   int i;
   /* Start at i = 1 to skip the command name. */
   for (i = 1; i < argc; i++) {
       /* Check for a switch (leading "-"). */
         if (argv[i][0] == '-') {
           /* Use the next character to decide what to do. */
           switch (argv[i][1]) {
		case 'a':	*a_value = atoi(argv[++i]);
				break;
		case 'b':	*b_value = atof(argv[++i]);
				break;
		default:	fprintf(stderr,"Unknown switch %s\n", argv[i]);
	    }
	}
    }
 }
main(int argc, char** argv)
{
   /* Set defaults for all parameters: */
   int a = 0;
   float b = 0.0;
   get_args(argc, argv, &a, &b);
   printf("a = %d\n", a);
   printf("b = %f\n", b);
}

CLAMPANDO PARA UM MINIMO MAXIMO[editar | editar código-fonte]

 double clamp(double v,double in_m,double in_M,double out_m,double out_M)
 { 
   return out_m + ((v-in_m)/(in_M-in_m))*(out_M-out_m);
  };

LIMITANDO PARA UM MINIMO MAXIMO[editar | editar código-fonte]

double limit(double v,double in_m,double in_M)
{
  return (v>in_M)?(in_M):((v<in_m)?(in_m):(v));
}

CROSS PRODUCT[editar | editar código-fonte]

float a[3];
float b[3];
float axb[3];

axb[0]=(a[1]*b[2]-a[2]*b[1]);
axb[1]=(a[2]*b[0]-a[0]*b[2]);
axb[2]=(a[0]*b[1]-a[1]*b[0]);

USING gluUnProject (OpenGL, gluUnProject, glut)[editar | editar código-fonte]

I have been using OpenGL since a long time and a fundamental problem many would like is how to find out where the user clicked in the 3D-world given the mouse co-ordinates. OpenGL and GLU functions can be used to effectively solve this problem. Since i could not find any good tutorials regarding this i thought i'd put up one by myself.

There is a simple function that glu provides. It's called gluUnProject, this function takes in 6 arguments.. which include the window x,y,z co-ordinates, modelview matrix, projection matrix, viewport and X,Y,Z for storing the world co-ordinates of that particular point. Dont' get worried about window z co-ordinate which is given to this function. This value is obtained by using glReadPixels( x, viewport[3]-y, GL_DEPTH_COMPONENT, GL_FLOAT, &z ); We need to use viewport[3]-y (this is equivalent to windowheight-y where x,y are the mouse location co-ordinates) instead of just y because the glut window has origin at top left corner where as OpenGL (glReadPixels) has the origin at bottom left corner.

Once you get the z value of the window (using glReadPixels), we can pass the window x,y,z values to the gluUnProject and get the world co-ordinates. In the example here a red cube is moved to the location where the user clicks on the green plane.

double objx, objy, objz;
//The drawing function glutDisplayFunc( )
void display( )
{
   //Clearing the screen with black and clearing the depth buffer
   glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );

   //The green polygon
   glBegin( GL_POLYGON );
   glColor3f( 0, 1, 0 );
   glVertex3f( -100, 0,  100  );
   glVertex3f( -100, 0, -100  );
   glVertex3f( 100,  0, -100 );
   glVertex3f( 100,  0, 100 );
   glEnd( );

   //store the current transformation matrix
   //and translate the cube to the world location
   glPushMatrix( );
       glColor3f( 1, 0, 0 );
       glTranslatef( objx, objy, objz );
       glutSolidCube( 10 );
   glPopMatrix( );

   glFlush( );
   glutSwapBuffers( );
}	

//The function that handles the mouse clicks glutMouseFunc( )
void mouse( int button, int state, int x, int y )
{
   double modelview[16], projection[16];
   int viewport[4];
   float z;
   //get the projection matrix		
   glGetDoublev( GL_PROJECTION_MATRIX, projection );
   //get the modelview matrix		
   glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
   //get the viewport		
   glGetIntegerv( GL_VIEWPORT, viewport );
	
   //Read the window z co-ordinate 
   //(the z value on that point in unit cube)		
   glReadPixels( x, viewport[3]-y, 1, 1,
             GL_DEPTH_COMPONENT, GL_FLOAT, &z );

   //Unproject the window co-ordinates to 
   //find the world co-ordinates.
   gluUnProject( x, viewport[3]-y, z, modelview, 
              projection, viewport, &objx, &objy, &objz );
}
Esta página é um monomódulo, ou seja, não está inserida em nenhum livro e/ou não tem subpáginas.
Ajude o Wikilivros inserindo-a em um livro existente ou por criar.