Cpp

Alex Laier - Fast Cpp

Apenas um pequeno teste


//***************************************************************************

//C++ FAST REFERENCE

//***************************************************************************


//***************************************************************************

//PREPROCESSOR

//***************************************************************************

// Comment to end of line

/* Multi-line comment */

#include <stdio.h> // Insert standard header file

#include "myfile.h" // Insert file in current directory

#define X some text // Replace X with some text

#define F(a,b) a+b // Replace F(1,2) with 1+2

#define X \

some text // Line continuation

#undef X // Remove definition

#if defined(X) // Condional compilation (#ifdef X)

#else // Optional (#ifndef X or #if !defined(X))

#endif // Required after #if, #ifdef


//***************************************************************************

//LITERALS

//***************************************************************************


255, 0377, 0xff // Integers (decimal, octal, hex)

2147483647L, 0x7fffffffl // Long (32-bit) integers

123.0, 1.23e2 // double (real) numbers

'a', '\141', '\x61' // Character (literal, octal, hex)

'\n', '\\', '\'', '\"' // Newline, backslash, single quote, double quote

"string\n" // Array of characters ending with newline and \0

"hello" "world" // Concatenated strings

true, false // bool constants 1 and 0


//***************************************************************************

//DECLARATIONS

//***************************************************************************


int x; // Declare x to be an integer (value undefined)

int x=255; // Declare and initialize x to 255

short s; long l; // Usually 16 or 32 bit integer (int may be either)

char c='a'; // Usually 8 bit character

unsigned char u=255; signed char s=-1; // char might be either

unsigned long x=0xffffffffL; // short, int, long are signed

float f; double d; // Single or double precision real (never unsigned)

bool b=true; // true or false, may also use int (1 or 0)

int a, b, c; // Multiple declarations

int a[10]; // Array of 10 ints (a[0] through a[9])

int a[]={0,1,2}; // Initialized array (or a[3]={0,1,2}; )

int a[2][3]={{1,2,3},{4,5,6}}; // Array of array of ints

char s[]="hello"; // String (6 elements including '\0')

int* p; // p is a pointer to (address of) int

char* s="hello"; // s points to unnamed array containing "hello"

void* p=NULL; // Address of untyped memory (NULL is 0)

int& r=x; // r is a reference to (alias of) int x

enum weekend {SAT,SUN}; // weekend is a type with values SAT and SUN

enum weekend day; // day is a variable of type weekend

enum weekend {SAT=0,SUN=1}; // Explicit representation as int

enum {SAT,SUN} day; // Anonymous enum

typedef String char*; // String s; means char* s;

const int c=3; // Constants must be initialized, cannot assign to

const int* p=a; // Contents of p (elements of a) are constant

int* const p=a; // p (but not contents) are constant

const int* const p=a; // Both p and its contents are constant

const int& cr=x; // cr cannot be assigned to change x


//***************************************************************************

//STORAGE CLASSES

//***************************************************************************


int x; // Auto (memory exists only while in scope)

static int x; // Global lifetime even if local scope

extern int x; // Information only, declared elsewhere


//***************************************************************************

//STATEMENTS

//***************************************************************************


x=y; // Every expression is a statement

int x; // Declarations are statements

; // Empty statement


{ // A block is a single statement

int x; // Scope of x is from declaration to end of block

a; // In C, declarations must precede statements

}


if (x) a; // If x is true (not 0), evaluate a

else if (y) b; // If not x and y (optional, may be repeated)

else c; // If not x and not y (optional)


while (x) a; // Repeat 0 or more times while x is true


for (x; y; z) a; // Equivalent to: x; while(y) {a; z;}


do a; while (x); // Equivalent to: a; while(x) a;


switch (x) { // x must be int

case X1: a; // If x == X1 (must be a const), jump here

case X2: b; // Else if x == X2, jump here

default: c; // Else jump here (optional)

}


break; // Jump out of while, do, or for loop, or switch

continue; // Jump to bottom of while, do, or for loop

return x; // Return x from function to caller


try { a; }

catch (T t) { b; } // If a throws a T, then jump here

catch (...) { c; } // If a throws something else, jump here


//***************************************************************************

//FUNCTIONS

//***************************************************************************


int f(int x, int); // f is a function taking 2 ints and returning int

void f(); // f is a procedure taking no arguments

void f(int a=0); // f() is equivalent to f(0)

f(); // Default return type is int

inline f(); // Optimize for speed

f() { statements; } // Function definition (must be global)

T operator+(T x, T y); // a+b (if type T) calls operator+(a, b)

T operator-(T x); // -a calls function operator-(a)

T operator++(int); // postfix ++ or -- (parameter ignored)

extern "C" {void f();} // f() was compiled in C




Function parameters and return values may be of any type. A function must either be declared or defined before it is used. It may be declared first and defined later. Every program consists of a set of a set of global variable declarations and a set of function definitions (possibly in separate files), one of which must be:


int main() { statements... } or

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


argv is an array of argc strings from the command line. By convention, main returns status 0 if successful, 1 or higher for errors.


Functions with different parameters may have the same name (overloading). Operators except :: . .* ?: may be overloaded. Precedence order is not affected. New operators may not be created.


//***************************************************************************

//EXPRESSIONS

//***************************************************************************


Operators are grouped by precedence, highest first. Unary operators and assignment evaluate right to left. All others are left to right. Precedence does not affect order of evaluation, which is undefined. There are no run time checks for arrays out of bounds, invalid pointers, etc.


T::X // Name X defined in class T

N::X // Name X defined in namespace N

::X // Global name X


t.x // Member x of struct or class t

p->x // Member x of struct or class pointed to by p

a[i] // i'th element of array a

f(x,y) // Call to function f with arguments x and y

T(x,y) // Object of class T initialized with x and y

x++ // Add 1 to x, evaluates to original x (postfix)

x-- // Subtract 1 from x, evaluates to original x

typeid(x) // Type of x

typeid(T) // Equals typeid(x) if x is a T

dynamic_cast<T>(x) // Converts x to a T, checked at run time

static_cast<T>(x) // Converts x to a T, not checked

reinterpret_cast<T>(x) // Interpret bits of x as a T

const_cast<T>(x) // Converts x to same type T but not const


sizeof x // Number of bytes used to represent object x

sizeof(T) // Number of bytes to represent type T

++x // Add 1 to x, evaluates to new value (prefix)

--x // Subtract 1 from x, evaluates to new value

~x // Bitwise complement of x

!x // true if x is 0, else false (1 or 0 in C)

-x // Unary minus

+x // Unary plus (default)

&x // Address of x

*p // Contents of address p (*&x equals x)

new T // Address of newly allocated T object

new T(x, y) // Address of a T initialized with x, y

new T[x] // Address of allocated n-element array of T

delete p // Destroy and free object at address p

delete[] p // Destroy and free array of objects at p

(T) x // Convert x to T (obsolete, use .._cast<T>(x))


x * y // Multiply

x / y // Divide (integers round toward 0)

x % y // Modulo (result has sign of x)


x + y // Add, or &x[y]

x - y // Subtract, or number of elements from *x to *y


x << y // x shifted y bits to left (x * pow(2, y))

x >> y // x shifted y bits to right (x / pow(2, y))


x < y // Less than

x <= y // Less than or equal to

x > y // Greater than

x >= y // Greater than or equal to


x == y // Equals

x != y // Not equals


x & y // Bitwise and (3 & 6 is 2)


x ^ y // Bitwise exclusive or (3 ^ 6 is 5)


x | y // Bitwise or (3 | 6 is 7)


x && y // x and then y (evaluates y only if x (not 0))


x || y // x or else y (evaluates y only if x is false (0))


x = y // Assign y to x, returns new value of x

x += y // x = x + y, also -= *= /= <<= >>= &= |= ^=


x ? y : z // y if x is true (nonzero), else z


throw x // Throw exception, aborts if not caught


x , y // evaluates x and y, returns y (seldom used)



//***************************************************************************

//CLASSES

//***************************************************************************


class T { // A new type

private: // Section accessible only to T's member functions

protected: // Also accessable to classes derived from T

public: // Accessable to all

int x; // Member data

void f(); // Member function

void g() {return;} // Inline member function

void h() const; // Does not modify any data members

int operator+(int y); // t+y means t.operator+(y)

int operator-(); // -t means t.operator-()

T(): x(1) {} // Constructor with initialization list

T(const T& t): x(t.x) {} // Copy constructor

T& operator=(const T& t) {x=t.x; return *this; } // Assignment operator

~T(); // Destructor (automatic cleanup routine)

explicit T(int a); // Allow t=T(3) but not t=3

operator int() const {return x;} // Allows int(t)

friend void i(); // Global function i() has private access

friend class U; // Members of class U have private access

static int y; // Data shared by all T objects

static void l(); // Shared code. May access y but not x

class Z {}; // Nested class T::Z

typedef int V; // T::V means int

};

void T::f() { // Code for member function f of class T

this->x = x;} // this is address of self (means x=x;)

int T::y = 2; // Initialization of static member (required)

T::l(); // Call to static member

struct T { // Equivalent to: class T { public:

virtual void f(); // May be overridden at run time by derived class

virtual void g()=0; }; // Must be overridden (pure virtual)

class U: public T {}; // Derived class U inherits all members of base T

class V: private T {}; // Inherited members of T become private

class W: public T, public U {}; // Multiple inheritance

class X: public virtual T {}; // Classes derived from X have base T directly


All classes have a default copy constructor, assignment operator, and destructor, which perform the corresponding operations on each data member and each base class as shown above. There is also a default no-argument constructor (required to create arrays) if the class has no constructors. Constructors, assignment, and destructors do not inherit.


//***************************************************************************

//TEMPLATES

//***************************************************************************


template <class T> T f(T t); // Overload f for all types

template <class T> class X { // Class with type parameter T

X(T t); }; // A constructor

template <class T> X<T>::X(T t) {} // Definition of constructor

X<int> x(3); // An object of type "X of int"

template <class T, class U=T, int n=0> // Template with default parameters


//***************************************************************************

//NAMESPACES

//***************************************************************************


namespace N {class T {};} // Hide name T

N::T t; // Use name T in namespace N

using namespace N; // Make T visible without N::




//***************************************************************************

//FUNCTIONS POINTERS

//***************************************************************************

//Define a Function Pointer

//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------

// 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

//---------------------------------------------------------------------------

// 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

//---------------------------------------------------------------------------

int result1 = pt2Function (12, 'a', 'b'); // C short way

int result2 = (*pt2Function) (12, 'a', 'b'); // 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 ?

//---------------------------------------------------------------------------

// <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 ?

//---------------------------------------------------------------------------

// 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: 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 ?

//---------------------------------------------------------------------------


// 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;

}




//***************************************************************************

//C/C++ STANDARD LIBRARY

//***************************************************************************

Only the most commonly used functions are listed. Header files without .h are in namespace std. File names are actually lower case.


//---------------------------------------------------------------------------

//STDIO.H, CSTDIO (Input/output)

//---------------------------------------------------------------------------

FILE* f=fopen("filename", "r"); // Open for reading, NULL (0) if error

// Mode may also be "w" (write) "a" append, "a+" update, "rb" binary

fclose(f); // Close file f

fprintf(f, "x=%d", 3); // Print "x=3" Other conversions:

"%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); // Print to array of char s

printf("x=%d", 3); // Print to stdout (screen unless redirected)

fprintf(stderr, ... // Print to standard error (not redirected)

getc(f); // Read one char (as an int) or EOF from f

ungetc(c, f); // Put back one c to f

getchar(); // getc(stdin);

putc(c, f) // fprintf(f, "%c", c);

putchar(c); // putc(c, stdout);

fgets(s, n, f); // Read line into char s[n] from f. NULL if EOF

gets(s) // fgets(s, INT_MAX, f); no bounds check

fread(s, n, 1, f); // Read n bytes from f to s, return number read

fwrite(s, n, 1, f); // Write n bytes of s to f, return number written

fflush(f); // Force buffered writes to f

fseek(f, n, SEEK_SET); // Position binary file f at n

ftell(f); // Position in f, -1L if error

rewind(f); // fseek(f, 0L, SEEK_SET); clearerr(f);

feof(f); // Is f at end of file?

ferror(f); // Error in f?

perror(s); // Print char* s and error message

clearerr(f); // Clear error code for f

remove("filename"); // Delete file, return 0 if OK

rename("old", "new"); // Rename file, return 0 if OK

f = tmpfile(); // Create temporary file in mode "wb+"

tmpnam(s); // Put a unique file name in char s[L_tmpnam]


//---------------------------------------------------------------------------

//STDLIB.H, CSTDLIB (Misc. functions)

//---------------------------------------------------------------------------


atof(s); atol(s); atoi(s);// Convert char* s to float, long, int

rand(), srand(seed); // Random int 0 to RAND_MAX, reset rand()

void* p = malloc(n); // Allocate n bytes. Obsolete: use new

free(p); // Free memory. Obsolete: use delete

exit(n); // Kill program, return status n

system(s); // Execute OS command s (system dependent)

getenv("PATH"); // Environment variable or 0 (system dependent)

abs(n); labs(ln); // Absolute value as int, long


//---------------------------------------------------------------------------

//STRING.H, CSTRING (Character array handling functions)

//---------------------------------------------------------------------------


Strings are type char[] with a '\0' in the last element used.


strcpy(dst, src); // Copy string. Not bounds checked

strcat(dst, src); // Concatenate to dst. Not bounds checked

strcmp(s1, s2); // Compare, <0 if s1<s2, 0 if s1==s2, >0 if s1>s2

strncpy(dst, src, n); // Copy up to n chars, also strncat(), strncmp()

strlen(s); // Length of s not counting \0

strchr(s,c); strrchr(s,c);// Address of first/last char c in s or 0

strstr(s, sub); // Address of first substring in s or 0

// mem... functions are for any pointer types (void*), length n bytes

memmove(dst, src, n); // Copy n bytes from src to dst

memcmp(s1, s2, n); // Compare n bytes as in strcmp

memchr(s, c, n); // Find first byte c in s, return address or 0

memset(s, c, n); // Set n bytes of s to c


//---------------------------------------------------------------------------

//CTYPE.H, CCTYPE (Character types)

//---------------------------------------------------------------------------


isalnum(c); // Is c a letter or digit?

isalpha(c); isdigit(c); // Is c a letter? Digit?

islower(c); isupper(c); // Is c lower case? Upper case?

tolower(c); toupper(c); // Convert c to lower/upper case


//---------------------------------------------------------------------------

//MATH.H, CMATH (Floating point math)

//---------------------------------------------------------------------------


sin(x); cos(x); tan(x); // Trig functions, x (double) is in radians

asin(x); acos(x); atan(x);// Inverses

atan2(y, x); // atan(y/x)

sinh(x); cosh(x); tanh(x);// Hyperbolic

exp(x); log(x); log10(x); // e to the x, log base e, log base 10

pow(x, y); sqrt(x); // x to the y, square root

ceil(x); floor(x); // Round up or down (as a double)

fabs(x); fmod(x, y); // Absolute value, x mod y


//---------------------------------------------------------------------------

//TIME.H, CTIME (Clock)

//---------------------------------------------------------------------------


clock()/CLOCKS_PER_SEC; // Time in seconds since program started

time_t t=time(0); // Absolute time in seconds or -1 if unknown

tm* p=gmtime(&t); // 0 if UCT unavailable, else p->tm_X where X is:

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)); // Same format, local time


//---------------------------------------------------------------------------

//ASSERT.H, CASSERT (Debugging aid)

//---------------------------------------------------------------------------


assert(e); // If e is false, print message and abort

#define NDEBUG // (before #include <assert.h>), turn off assert


NEW.H, NEW (Out of memory handler)


set_new_handler(handler); // Change behavior when out of memory

void handler(void) {throw bad_alloc();} // Default


//---------------------------------------------------------------------------

//IOSTREAM.H, IOSTREAM (Replaces stdio.h)

//---------------------------------------------------------------------------


cin >> x >> y; // Read words x and y (any type) from stdin

cout << "x=" << 3 << endl; // Write line to stdout

cerr << x << y << flush; // Write to stderr and flush

c = cin.get(); // c = getchar();

cin.get(c); // Read char

cin.getline(s, n, '\n'); // Read line into char s[n] to '\n' (default)

if (cin) // Good state (not EOF)?

// To read/write any type T:

istream& operator>>(istream& i, T& x) {i >> ...; x=...; return i;}

ostream& operator<<(ostream& o, const T& x) {return o << ...;}


//---------------------------------------------------------------------------

//FSTREAM.H, FSTREAM (File I/O works like cin, cout as above)

//---------------------------------------------------------------------------


ifstream f1("filename"); // Open text file for reading

if (f1) // Test if open and input available

f1 >> x; // Read object from file

f1.get(s); // Read char or line

f1.getline(s, n); // Read line into string s[n]

ofstream f2("filename"); // Open file for writing

if (f2) f2 << x; // Write to file


//---------------------------------------------------------------------------

//IOMANIP.H, IOMANIP (Output formatting)

//---------------------------------------------------------------------------


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


//---------------------------------------------------------------------------

//STRING (Variable sized character array)

//---------------------------------------------------------------------------


string s1, s2="hello"; // Create strings

s1.size(), s2.size(); // Number of characters: 0, 5

s1 += s2 + ' ' + "world"; // Concatenation

s1 == "hello world" // Comparison, also <, >, !=, etc.

s1[0]; // 'h'

s1.substr(m, n); // Substring of size n starting at s1[m]

s1.c_str(); // Convert to const char*

getline(cin, s); // Read line ending in '\n'


//---------------------------------------------------------------------------

//VECTOR (Variable sized array/stack with built in memory allocation)

//---------------------------------------------------------------------------


vector<int> a(10); // a[0]..a[9] are int (default size is 0)

a.size(); // Number of elements (10)

a.push_back(3); // Increase size to 11, a[10]=3

a.back()=4; // a[10]=4;

a.pop_back(); // Decrease size by 1

a.front(); // a[0];

a[20]=1; // Crash: not bounds checked

a.at(20)=1; // Like a[20] but throws out_of_range()

for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p)

*p=0; // Set all elements of a to 0

vector<int> b(a.begin(), a.end()); // b is copy of a

vector<T> c(n, x); // c[0]..c[n-1] init to x

T d[10]; vector<T> e(d, d+10); // e is initialized from d


//---------------------------------------------------------------------------

//DEQUE (array/stack/queue)

//---------------------------------------------------------------------------


deque<T> is like vector<T>, but also supports:


a.push_front(x); // Puts x at a[0], shifts elements toward back

a.pop_front(); // Removes a[0], shifts toward front


//---------------------------------------------------------------------------

//UTILITY (Pair)

//---------------------------------------------------------------------------


pair<string, int> a("hello", 3); // A 2-element struct

a.first; // "hello"

a.second; // 3


//---------------------------------------------------------------------------

//MAP (associative array)

//---------------------------------------------------------------------------


map<string, int> a; // Map from string to int

a["hello"]=3; // Add or replace element 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 (A collection of 60 algorithms on sequences with iterators)

//---------------------------------------------------------------------------

min(x, y); max(x, y); // Smaller/larger of x, y (any type defining <)

swap(x, y); // Exchange values of variables x and y

sort(a, a+n); // Sort array a[0]..a[n-1] by <

sort(a.begin(), a.end()); // Sort vector or deque


//***************************************************************************

//C++ SNIPPETS/SAMPLES

//***************************************************************************


//---------------------------------------------------------------------------

//SINGLETON

//---------------------------------------------------------------------------

//: 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;

} ///:~


//---------------------------------------------------------------------------

//READING A TEXT FILE

//---------------------------------------------------------------------------

#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;

}



//---------------------------------------------------------------------------

// WRITING A TEXT FILE

//---------------------------------------------------------------------------

#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

//---------------------------------------------------------------------------

#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

//---------------------------------------------------------------------------

#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;

}



//---------------------------------------------------------------------------

//ARVORE BINÁRIA

//---------------------------------------------------------------------------

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 IEEE AND MICROSOFT FLOAT

//---------------------------------------------------------------------------


#include /* for strncpy */

int _fmsbintoieee(float *src4, float *dest4)

{

unsigned char *msbin = (unsigned char *)src4;

unsigned char *ieee = (unsigned char *)dest4;

unsigned char sign = 0x00;

unsigned char ieee_exp = 0x00;

int i;

/* MS Binary Format */

/* byte order => m3 | m2 | m1 | exponent */

/* m1 is most significant byte => sbbb|bbbb */

/* m3 is the least significant byte */

/* m = mantissa byte */

/* s = sign bit */

/* b = bit */

sign = msbin[2] & 0x80; /* 1000|0000b */

/* IEEE Single Precision Float Format */

/* m3 m2 m1 exponent */

/* mmmm|mmmm mmmm|mmmm emmm|mmmm seee|eeee */

/* s = sign bit */

/* e = exponent bit */

/* m = mantissa bit */

for (i=0; i<4; i++) ieee[i] = 0;

/* any msbin w/ exponent of zero = zero */

if (msbin[3] == 0) return 0;

ieee[3] |= sign;

/* MBF is bias 128 and IEEE is bias 127. ALSO, MBF places */

/* the decimal point before the assumed bit, while */

/* IEEE places the decimal point after the assumed bit. */

ieee_exp = msbin[3] - 2; /* actually, msbin[3]-1-128+127 */

/* the first 7 bits of the exponent in ieee[3] */

ieee[3] |= ieee_exp >> 1;

/* the one remaining bit in first bin of ieee[2] */

ieee[2] |= ieee_exp << 7;

/* 0111|1111b : mask out the msbin sign bit */

ieee[2] |= msbin[2] & 0x7f;

ieee[1] = msbin[1];

ieee[0] = msbin[0];

return 0;

}


//---------------------------------------------------------------------------

//CONVERTING BETWEEN IEEE AND MICROSOFT FLOAT

//---------------------------------------------------------------------------


int _fieeetomsbin(float *src4, float *dest4)

{

unsigned char *ieee = (unsigned char *)src4;

unsigned char *msbin = (unsigned char *)dest4;

unsigned char sign = 0x00;

unsigned char msbin_exp = 0x00;

int i;

/* See _fmsbintoieee() for details of formats */

sign = ieee[3] & 0x80;

msbin_exp |= ieee[3] << 1;

msbin_exp |= ieee[2] >> 7;

/* An ieee exponent of 0xfe overflows in MBF */

if (msbin_exp == 0xfe) return 1;

msbin_exp += 2; /* actually, -127 + 128 + 1 */

for (i=0; i<4; i++) msbin[i] = 0;

msbin[3] = msbin_exp;

msbin[2] |= sign;

msbin[2] |= ieee[2] & 0x7f;

msbin[1] = ieee[1];

msbin[0] = ieee[0];

return 0;

}


//---------------------------------------------------------------------------

//CONVERTING BETWEEN IEEE AND MICROSOFT DOUBLE

//---------------------------------------------------------------------------


int _dmsbintoieee(double *src8, double *dest8)

{

unsigned char msbin[8];

unsigned char *ieee = (unsigned char *)dest8;

unsigned char sign = 0x00;

unsigned int ieee_exp = 0x0000;

int i;

/* A manipulatable copy of the msbin number */

strncpy((char *)msbin,(char *)src8,8);

/* MS Binary Format */

/* byte order => m7 | m6 | m5 | m4 | m3 | m2 | m1 | exponent */

/* m1 is most significant byte => smmm|mmmm */

/* m7 is the least significant byte */

/* m = mantissa byte */

/* s = sign bit */

/* b = bit */

sign = msbin[6] & 0x80; /* 1000|0000b */

/* IEEE Single Precision Float Format */

/* byte 8 byte 7 byte 6 byte 5 byte 4 and so on */

/* seee|eeee eeee|mmmm mmmm|mmmm mmmm|mmmm mmmm|mmmm ... */

/* s = sign bit */

/* e = exponent bit */

/* m = mantissa bit */

for (i=0; i<8; i++) ieee[i] = 0;

/* any msbin w/ exponent of zero = zero */

if (msbin[7] == 0) return 0;

ieee[7] |= sign;

/* MBF is bias 128 and IEEE is bias 1023. ALSO, MBF places */

/* the decimal point before the assumed bit, while */

/* IEEE places the decimal point after the assumed bit. */

ieee_exp = msbin[7] - 128 - 1 + 1023;

/* First 4 bits of the msbin exponent */

/* go into the last 4 bits of ieee[7] */

ieee[7] |= ieee_exp >> 4;

/* The last 4 bits of msbin exponent */

/* go into the first 4 bits of ieee[6] */

ieee[6] |= ieee_exp << 4;

/* The msbin mantissa must be shifted to the right 1 bit. */

/* Remember that the msbin number has its bytes reversed. */

for (i=6; i>0; i--)

{

msbin[i] <<= 1;

msbin[i] |= msbin[i-1] >> 7;

}

msbin[0] <<= 1;

/* Now the mantissa is put into the ieee array starting in */

/* the middle of the second to last byte. */

for (i=6; i>0; i--)

{

ieee[i] |= msbin[i] >> 4;

ieee[i-1] |= msbin[i] << 4;

}

ieee[0] |= msbin[0] >> 4;

/* IEEE has a half byte less for its mantissa. If the msbin */

/* number has anything in this last half byte, then there is */

/* an overflow. */

if (msbin[0] & 0x0f)

return 1;

else

return 0;

}


//---------------------------------------------------------------------------

//CONVERTING BETWEEN IEEE AND MICROSOFT DOUBLE

//---------------------------------------------------------------------------


int _dieeetomsbin(double *src8, double *dest8)

{

unsigned char ieee[8];

unsigned char *msbin = (unsigned char *)dest8;

unsigned char sign = 0x00;

unsigned char any_on = 0x00;

unsigned int msbin_exp = 0x0000;

int i;

/* Make a clobberable copy of the source number */

strncpy((char *)ieee,(char *)src8,8);

for (i=0; i<8; i++) msbin[i] = 0;

/* If all are zero in src8, the msbin should be zero */

for (i=0; i<8; i++) any_on |= ieee[i];

if (!any_on) return 0;

sign = ieee[7] & 0x80;

msbin[6] |= sign;

msbin_exp = (unsigned)(ieee[7] & 0x7f) * 0x10;

msbin_exp += ieee[6] >> 4;

if (msbin_exp-0x3ff > 0x80) return 1;

msbin[7] = msbin_exp - 0x3ff + 0x80 + 1;

/* The ieee mantissa must be shifted up 3 bits */

ieee[6] &= 0x0f; /* mask out the exponent in the second byte

*/

for (i=6; i>0; i--)

{

msbin[i] |= ieee[i] << 3;

msbin[i] |= ieee[i-1] >> 5;

}

msbin[0] |= ieee[0] << 3;

return 0;

}


//---------------------------------------------------------------------------

//CONVERTING BETWEEN BIG AND LITLE ENDIAN word 16 bits and Dword 32 bits

//---------------------------------------------------------------------------

#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

//---------------------------------------------------------------------------

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();


//---------------------------------------------------------------------------

//SIMPLE GEOSIS SURFACE FROM PHOTOSHOP RAW 8 BITS 1 CAMADA

//---------------------------------------------------------------------------

#include <stdio.h>

#include <iostream>

#include <fstream>

#include <float.h>

#include <cmath>

#include <ctime>

#include <gsVoxet.h>

#include <gsFilter.h>

#include <gsSurface.h>


int main()

{

const char * filename = "F:\\dev\\test01\\files\\heart_0000.raw";

const char * surfname = "F:\\dev\\test01\\files\\heart.ply";


char s[31][256] = {"F:\\dev\\test01\\files\\heart_0000.raw",

"F:\\dev\\test01\\files\\heart_0001.raw",

"F:\\dev\\test01\\files\\heart_0002.raw",

"F:\\dev\\test01\\files\\heart_0003.raw",

"F:\\dev\\test01\\files\\heart_0004.raw",

"F:\\dev\\test01\\files\\heart_0005.raw",

"F:\\dev\\test01\\files\\heart_0006.raw",

"F:\\dev\\test01\\files\\heart_0007.raw",

"F:\\dev\\test01\\files\\heart_0008.raw",

"F:\\dev\\test01\\files\\heart_0009.raw",

"F:\\dev\\test01\\files\\heart_0010.raw",

"F:\\dev\\test01\\files\\heart_0011.raw",

"F:\\dev\\test01\\files\\heart_0012.raw",

"F:\\dev\\test01\\files\\heart_0013.raw",

"F:\\dev\\test01\\files\\heart_0014.raw",

"F:\\dev\\test01\\files\\heart_0015.raw",

"F:\\dev\\test01\\files\\heart_0016.raw",

"F:\\dev\\test01\\files\\heart_0017.raw",

"F:\\dev\\test01\\files\\heart_0018.raw",

"F:\\dev\\test01\\files\\heart_0019.raw",

"F:\\dev\\test01\\files\\heart_0021.raw",

"F:\\dev\\test01\\files\\heart_0022.raw",

"F:\\dev\\test01\\files\\heart_0023.raw",

"F:\\dev\\test01\\files\\heart_0024.raw",

"F:\\dev\\test01\\files\\heart_0025.raw",

"F:\\dev\\test01\\files\\heart_0026.raw",

"F:\\dev\\test01\\files\\heart_0027.raw",

"F:\\dev\\test01\\files\\heart_0028.raw",

"F:\\dev\\test01\\files\\heart_0029.raw",

"F:\\dev\\test01\\files\\heart_0030.raw",

"F:\\dev\\test01\\files\\heart_0031.raw" } ;

std::cout << "Teste de velocidade de construção de isosuperfície\n" ;


gsVoxet myvoxet(300,300,10);

myvoxet.addProperty();




for (int i = 0;i<30;++i)

{

char * buffer;

long size;

filename = s[i];

std::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 << "lendo arquivo:" << s[i] << "\n";

for (int y=0;y<300;y++)

for (int x=0;x<300;x++)

{

int k = (unsigned char )buffer[300*y+x];

myvoxet.setValue(x,y,i,(float)k);

}


delete[] buffer;

}

gsFilterIsovalue* F = new gsFilterIsovalue(&myvoxet,0.5);


gsSurface mysurf(F);

mysurf.writePLY(surfname);

delete F;


std::cout <<"\n Press [ENTER] to exit.";

char c ;

std::cin.get(c);


return(0);

}