0% found this document useful (0 votes)
7 views

C++ CPP Reference

Uploaded by

señor oscuro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

C++ CPP Reference

Uploaded by

señor oscuro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

C++ Reference Natsis Athanasios, Νάτσης Θανάσης cb e a 1/4

LITERALS
int arry[n];
ARRAYS
// array of size n
OPERATORS PREPROCESSOR DIRECTIVES
255, 0377, 0xff Integers (decimal, octal, hex) priority/operator/desc/ASSOCIATIVITY #define ID value // replaces ID with
int arry2d[n][m]; // 2d n x m array
2147483647L, Long (32-bit) integers int arry3d[i][j][k]; // 3d i x j x k array 1 :: scope LEFT //value for each occurrence in the code
0x7fffffffl
#undef ID // reverse of #define
2 () parenthesis LEFT #ifdef ID //executes code if ID defined
123.0, 1.23e2 double (real) numbers
STRUCTURES
struct name { [] brackets LEFT #ifndef ID // opposite of #ifdef
’a’, ’\141’, ’\x61’ Character (literal, octal, hex) type1 element1; #if expr // executes if expr is true
-> pointer reference LEFT
type2 element2; #else // else
’\n’, ’\\’, ’\’’, ’\"’ Newline, backslash, single quote, .
int anum; structure member access LEFT #elif // else if
double quote
char achar; sizeof returns memory size LEFT #endif // ends if block
”string\n” Array of characters ending with } object_name; // instance of name #line number “filename” // #line controls what line number
name variable; // variable of type name 3 ++ increment RIGHT // and filename appear when compiler
newline and \0
variable.element1; // ref. of element -- decrement RIGHT // error occurs
”hello” ”world” Concatenated strings
variable->element1; // reference of pointed to structure ~ complement to one (bitwise) RIGHT #error msg //reports msg on cmpl. error
true, false bool constants 1 and 0 #include “file” // inserts file into code
! unary NOT RIGHT // during compilation
STORAGE CLASSES
#pragma //passes parameters to compiler
int x; Auto (memory exists only while in scope) INITIALIZATION & reference (pointers) RIGHT
#include <stdio.h> // Insert standard header file
type id; // declaration * dereference RIGHT
static int x; Global lifetime even if local scope #include "myfile.h" // Insert file in current directory
type id,id,id; // multiple declaration (type) type casting RIGHT #define F(a,b) a+b // Replace F(1,2) with 1+2
extern int x; Information only, declared elsewhere type *id; // pointer declaration
type id = value; // declare with assign + - unary less sign RIGHT #undef X // Remove definition
C++ PROGRAM STRUCTURE #if defined(X) // Condional compilation (#ifdef X)
// my first program in C++ type *id = value; // pointer with assign 4 * multiply LEFT
id = value; // assignment #else // Optional (#ifndef X or #if !defined(X))
#include <iostream.h>
/ divide LEFT #endif // Required after #if, #ifdef
#define X \
some text // Line continuation EXAMPLES % modulus LEFT
char c='A'; // single character in single quotes
int main () { char *str = "Hello"; // string in double quotes, 5 + addition LEFT
int x; // Scope of x is from // pointer to string
// declaration to end of block int i = 1022;
- subtraction LEFT CONTROL STRUCTURES
cout << "Hello World!"; // Every expression float f = 4.0E10; // 4^10
6 << bitwise shift left LEFT DECISION (if-else)
// is a statement int a[10]; // Array of 10 ints a[0]-a[9] >> bitwise shift right LEFT
return 0; if (condition) {
int ary[2] = {1,2}; // Array of ints < statements;
} 7 less than LEFT
int a[]={0,1,2}; // Initialized array a[3]={0,1,2}; }
/* multi-line int a[2][3]={{1,2,3},{4,5,6}}; // Array of array of ints <= less than or equal LEFT
comment */ else if (condition) {
const int a = 45; // constant declaration > greater than LEFT statements;
struct products { // declaration }
IDENTIFIERS >= greater than or equal LEFT
ANSI C++ reserved words, cannot be used as variable names. char name [30]; else {
asm, auto, bool, break, case, catch, char, class, float price; 8 == equal LEFT statements;
const, const_cast, continue, default, delete, do, }; }
!= not equal LEFT
double, dynamic_cast, else, enum, explicit, extern, products apple; // create instance if (x == 3) // curly braces not needed
false, float, for, friend, goto, if, inline, int, apple.name = "Macintosh"; // assignment 9 & bitwise AND LEFT flag = 1; // when if statement is
long, mutable, namespace, new, operator, private, apple.price = 0.45; ^ bitwise NOT LEFT else // followed by only one
protected, public, register, reinterpret_cast, products *pApple; // pointer to struct flag = 0; // statement
| bitwise OR LEFT
return, short, signed, sizeof, static, static_cast, pApple->name = "Granny Smith";
struct, switch, template, this, throw, true, try, pApple->price = 0.35; // assignment 10 && logical AND LEFT REPETITION (while)
typedef, typeid, typename, union, unsigned, using, short s; long l; // Usually 16 or 32 bit integer while (expression) { // loop until
|| logical OR LEFT
virtual, void, volatile, wchar_t // (int may be either) statements; // expression is false
unsigned char u=255; 11 ? : conditional RIGHT }
signed char s=-1; // char might be either
12 = assignment
unsigned long x=0xffffffffL; // short, int, long REPETITION (do-while)
DATA TYPES // are signed += add/assign
do { // perform the statements
VARIABLE DECLARATION float f; double d; // Single or double precision real -= subtract/assign statements; // as long as condition
special class size sign type name; // (never unsigned)
} while (condition); // is true
volatile // special bool b=true; // true or false, may use int (1 or 0) *= multiply/assign
register, static, extern, auto // class int* p; // p is a pointer to (address of) int /= divide/assign REPETITION (for)
long, short, double // size char* s="hello"; // s points to unnamed array
signed, unsigned // sign // containing "hello" %= modulus/assign init initial value for loop control variable
int, float, char // type (required) void* p=NULL; // Address of untyped memory (NULL is 0) >>= bitwise shift right/assign condition stay in the loop as long as condition is true
the_variable_name // name (required) int& r=x; // r is a reference to (alias of) int x
<<= bitwise shift left/assign change the loop control variable
// example of variable declaration enum weekend {SAT,SUN}; // weekend is a type with values increment
extern short unsigned char AFlag; // SAT and SUN &= bitwise AND/assign
enum weekend day; // day is a variable of type weekend for(init; condition; increment) {
TYPE SIZE RANGE ^= bitwise NOT/assign
enum weekend {SAT=0,SUN=1};// Explicit representation as int statements;
signed -128...127 enum {SAT,SUN} day; // Anonymous enum |= bitwise OR/assign }
char 1
unsigned 0...255 typedef String char*; // String s; means char* s; ,
13 comma
signed -32768...32767 const int c=3; // Constants must be initialized, BIFURCATION (break, continue, goto, exit)
short 2
unsigned 0...65535 // cannot assign to break; // ends a loop
const int* p=a; // Contents of p (elements of a) USER DEFINED DATATYPES continue; // stops executing statements in current
signed -2147483648...2147483647 // are constant // iteration of loop continues executing
long 4 typedef existingtype newtypename;
unsigned 0...4294967295 int* const p=a; // p (but not contents) are constant typedef unsigned int WORD; // on next iteration
varies depending on system const int* const p=a; // Both p and its contents enum name{val1, val2, ...} obj_name; label:
int
// are constant enum days_t {MON,WED,FRI} days; goto label; // execution continues at label
float 4 3.4E +/- 38 ( 7 digits) const int& cr=x; // cr cannot be assigned to change x union model_name { exit(retcode); // exits program
double 8 1.7E +/- 308 (15 digits) type1 element1;
long double 1.2E +/- 4932 (19 digits) type2 element2; SELECTION (switch)
10
bool 1 true or false EXCEPTIONS ... switch (variable) {
try { } object_name ; case constant1: // chars, ints
wchar_t 2 wide characters // code to be tried union mytypes_t { statements;
POINTERS statements; // if statements fail, exception is set char c; break; // needed to end flow
type *variable; // pointer to variable throw exception; int i; case constant2:
type *func(); // function returns pointer } } mytypes; statements;
void * // generic pointer type catch (type exception) { struct packed { // bit fields break;
NULL; // null pointer // code in case of exception unsigned int flagA:1; // flagA is 1 bit default:
*ptr; // object pointed to by pointer statements; unsigned int flagB:3; // flagB is 3 bit statements; // default statements
&obj; // address of object } } }

¸ ¸ ¸
[email protected] programmingandmorestuff.blogspot.gr
C++ Reference Natsis Athanasios, Νάτσης Θανάσης cb e a 2/4

type return type of the function


CONSOLE I/O name name by which the function is called
NAMESPACES OVERLOADING OPERATORS
Like functions, operators can be overloaded. Imagine you have a
C STYLE CONSOLE I/O arg1, arg2 parameters to the function
Namespaces allow global identifiers under a name
class that defines a square and you create two instances of the
stdin standard input stream statement // simple namespace class. You can add the two objects together.
statements inside the function
stdout standard output stream namespace identifier { class CSquare { // declare a class
// example function declaration namespace body; public: // functions
stderr standard error stream // return type int } void Init(float h, float w);
int add(int a, int b) { // parms // example namespace float GetArea();
// print to screen with formatting
int r; // declaration namespace first {int var = 5;} CSquare operator + (CSquare);
printf("format", arg1,arg2,...);
r = a + b; // add nums namespace second {double var = 3.1416;} private: // overload the ‘+’ operator
printf("nums: \%d, \%f,\%c", 1, 5.6, 'C');
return r; // return value int main () { float h,w;
// print to string s
} cout << first::var << endl; }
sprintf(s, "format", arg1, arg2,...);
num = add(1,2); // function call cout << second::var << endl; // function implementations
sprintf(s, "This is string # \%i",2);
// read data from keyboard into return 0; void CSquare::Init(float hi, float wi){
// name1, name2,... PASSING PARAMETERS } h = hi; w = wi;
scanf("format", &name1, &name2, ...); // using namespace allows for the current nesting }
BY VALUE // level to use the appropriate namespace
scanf("\%d,\%f", var1, var2); // read nums float CSquare::GetArea() {
// read from string s using namespace identifier; return (h*w);
function(int var); // passed by value // example using namespace
sscanf("format", &name1, &name2, ...); }
sscanf(s, "\%i,\%c", var1, var2); Variable is passed into the function and can be changed, but namespace first {int var = 5;} // implementation of overloaded operator
changes are not passed back. namespace second {double var = 3.1416;} CSquare CSquare::operator+ (CSquare cs) {
C STYLE I/O FORMATTING int main () { CSquare temp; // create CSquare object
%d, %i integer
BY CONSTANT VALUE using namespace second; temp.h = h + cs.h; // add h and w to
function(const int var); // passed by constant cout << var << endl; temp.w = w + cs.w; // temp object
%c single character Variable is passed into the function but cannot be changed. cout << (var*2) << endl; return (temp);
%f double (float) return 0; }
BY REFERENCE } // object declaration and usage
%o octal
CSquare sqr1, sqr2, sqr3;
%p pointer function(int &var); // pass by reference
CLASS REFERENCE sqr1.Init(3,4); // initialize objects
%u unsigned Variable is passed into the function and can be changed, changes sqr2.Init(2,3);
are passed back.
CLASS SYNTAX sqr3 = sqr1 + sqr2; // object sqr3 is now (5,7)
%s char string
class classname {
%e, %E exponential BY CONSTANT REFERENCE public:
classname(parms); // constructor
%x, %X hexadecimal
function(const int &var); ~classname(); // destructor
ADVANCED CLASS SYNTAX
%n number of chars written
Variable cannot be changed in the function. member1; STATIC KEYWORD
%g, %G same as f for e,E member2; variables are the same throughout all instances of a
protected: static
C++ CONSOLE I/O ARRAY BY REFERENCE class.
It’s a waste of memory to pass arrays and structures by value, member3;
cout<< console out, printing to screen static int n; // declaration
instead pass by reference. ...
cin>> console in, reading from keyboard private: CDummy::n; // reference
int array[1]; // array declaration
cerr<< console error member4;
ret = aryfunc(&array); // function call VIRTUAL MEMBERS
} objectname;
clog<< console log int aryfunc(int *array[1]) { Classes may have virtual members. If the function is redefined
// constructor (initializes variables)
array[0] = 2; // function in an inherited class, the parent must have the word virtual in
cout<<"Please enter an integer: "; classname::classname(parms) {
return 2; // declaration front of the function definition
cin>>i; }
}
cout<<"num1: "<<i<<"\n"<<endl; // destructor (deletes variables)
classname::~classname() { THIS KEYWORD
DEFAULT PARAMETER VALUES The this keyword refers to the memory location of the current
CONTROL CHARACTERS }
object.
\b backspace \f form feed int add(int a, int b=2) { int func(this); // passes pointer to current object
members are accessible from anywhere where the
int r; public
\r return \’ apostrophe class is visible
r = a + b; // b is always 2 CLASS TYPECASTING
\n newline \t tab return (r); members are only accessible from members of the reinterpret_cast <newtype>(expression);
protected dynamic_cast <newtype>(expression);
\nnn character #nnn (octal) \” quote } same class or of a friend class
static_cast <newtype>(expression);
\NN character #NN (hexadecimal) members are accessible from members of the same
OVERLOADING FUNCTIONS const_cast <newtype>(expression);
private class, members of the derived classes and a friend
CHARACTER STRINGS Functions can have the same name, and same number of parameters
class EXPRESSION TYPE
The string “Hello” is actually composed of 6 characters and is as long as the parameters are of different types
The type of an expression can be found using typeid.
stored in memory as follows: // takes and returns integers may be overloaded just like any other function.
typeid(expression); // returns a type
Char: H e l l o \0 int divide (int a, int b) constructors define two identical constructors with difference
{ return (a/b); } parameter lists
Index: 0 1 2 3 4 5
// takes and returns floats
\0 (backslash zero) is the null terminator character and float divide (float a, float b) CLASS EXAMPLE INHERITANCE
determines the end of the string. A string is an array of { return (a/b); } class CSquare { // class declaration Functions from a class can be inherited and reused in other
characters. Arrays in C and C++ start at zero. divide(10,2); // returns 5 public: classes. Multiple inheritance is possible.
str = "Hello"; divide(10,3); // returns 3.33333333 void Init(float h, float w); class CPoly { //create base polygon class
str[2] = 'e'; // string is now ‘Heelo’ float GetArea(); // functions protected:
RECURSION private: // available only to CSquare int width, height;
common <string.h> functions: Functions can call themselves float h,w; public:
strcat(s1,s2) strchr(s1,c) strcmp(s1,s2) strcpy(s2,s1) long factorial (long n) { } void SetValues(int a, int b)
strlen(s1) strncpy(s2,s1,n) strstr(s1,s2) if (n > 1) // implementations of functions { width=a; height=b;}
return (n * factorial (n-1)); void CSquare::Init(float hi, float wi){ };
else h = hi; w = wi; class COutput { // create base output class
return (1); } public:
FUNCTIONS } float CSquare::GetArea() { void Output(int i);
In C, functions must be prototyped before the main function, and
return (h*w); };
defined after the main function. In C++, functions may, but do PROTOTYPING } void COutput::Output (int i) {
not need to be, prototyped. C++ functions must be defined before Functions can be prototyped so they can be used after being // example declaration and usage cout << i << endl;
the location where they are called from. declared in any order CSquare theSquare; }
// function declaration // prototyped functions can be used theSquare.Init(8,5); // CRect inherits SetValues from Cpoly
type name(arg1, arg2, ...) { // anywhere in the program area = theSquare.GetArea(); // and inherits Output from COutput
statement1; #include <iostream.h> // or using a pointer to the class class CRect: public CPoly, public COutput
statement2; void odd (int a); CSquare *theSquare; {
... void even (int a); theSquare->Init(8,5); public:
} int main () { ... } area = theSquare->GetArea(); int area(void)

¸ ¸ ¸
[email protected] programmingandmorestuff.blogspot.gr
C++ Reference Natsis Athanasios, Νάτσης Θανάσης cb e a 3/4

{ return (width * height); } FRIEND FUNCTIONS handle.seekg(offset, direction); C/C++ STANDARD LIBRARY
}; A friend function has the keyword friend in front of it. If it // seek a position in writing a file
// CTri inherits SetValues from CPoly is declared inside a class, that function can be called without handle.seekp(position); Only the most commonly used functions are listed. Header files
class CTri: public CPoly { handle.seekp(offset, direction); without .h are in namespace std. File names are actually lower
reference from an object. An object may be passed to it.
public: direction can be one of the following case.
int area(void) /* change can be used anywhere and can have a CRect
object passed in */ ios::beg beginning of the stream
{ return (width * height / 2); } STDIO.H, CSTDIO (Input/output
}; // this example defined inside a class ios::cur current position of the stream pointer
void main () { friend CRect change(CRect);
ios::end end of the stream FILE* f=fopen("filename", "r"); // Open for reading,
CRect rect; // declare objects CRectangle recta, rectb; // declaration
BINARY FILES // NULL (0) if error. Mode may also be "w" (write)
CTri tri; rectb = change(recta); // usage
// "a" append, "a+" update, "rb" binary
buffer a location to store the characters.
rect.SetValues (2,9); fclose(f); // Close file f
tri.SetValues (2,9); numbytes the number of bytes to written or read. fprintf(f, "x=%d", 3); // Print "x=3" Other conversions:
rect.Output(rect.area()); FILE I/O write(char *buffer, numbytes); "%5d %u %-8ld" // int width 5, unsigned int, long left just.
cout<<tri.area()<<endl; #include <fstream.h> // read/write file read(char *buffer, numbytes); "%o %x %X %lx" // octal, hex, HEX, long hex
} #include <ofstream.h> // write file "%f %5.1f" // float or double: 123.000000, 123.0
#include <ifstream.h> // read file OUTPUT FORMATTING "%e %g" // 1.23e2, use either f or g
File I/O is done from the classes fstream, ofstream, ifstream. streamclass f; // declare file handle "%c %s" // char, char*
f.flags(ios_base::flag) // set output flags "%%" // %
TEMPLATES FILE HANDLES possible flags sprintf(s, "x=%d", 3); // Print to array of char s
Templates allow functions and classes to be reused without A file must have a file handle (pointer to the file) to access dec fixed hex printf("x=%d", 3); // Print to stdout
overloading them the file.
oct scientific
fprintf(stderr, ...) // Print to standard error
internal
ifstream infile; // create handle called getc(f); // Read one char (as an int) or EOF from f
template <class id> function; left right uppercase
ungetc(c, f); // Put back one c to f
// infile to read from a file
template <typename id> function; getchar(); // getc(stdin);
ofstream outfile; // handle for writing boolalpha showbase showpoint
// ---------- function example --------- putc(c, f) // fprintf(f, "%c", c);
fstream f; // handle for read/write
template <class T> showpos skipws unitbuf
putchar(c); // putc(c, stdout);
T GetMax (T a, T b) { OPENING FILES adjustfield fgets(s, n, f); // Read line into char s[n] from f.
return (a>b?a:b); // return the larger After declaring a file handle, the following syntax can be used adjustfield left adjustfield right
internal // NULL if EOF
} to open the file gets(s) // fgets(s, INT_MAX, no bounds check
void main () { basefield dec basefield oct basefield hex
void open(const char *fname, ios::mode); fread(s, n, 1, f); // Read n bytes from f to s,
int a=9, b=2, c; floatfield
// return number read
should be a string, specifying an absolute or floatfield fixed
float x=5.3, y=3.2, z; fname scientific fwrite(s, n, 1, f); // Write n bytes of s to f,
c=GetMax(a,b); relative path, including filename
f.fill() // get fill character // return number written
z=GetMax(x,y); ios::in Open file for reading fflush(f); // Force buffered writes to f
f.fill(c h) // set fill character ch
} fseek(f, n, SEEK_SET);// Position binary file f at n
ios::out Open file for writing f.precision(ndigits) // sets the precision for floating
// ----------- class example ----------- ftell(f); // Position in f, -1L if error
// point numbers to ndigits
template <class T> ios::ate Initial position: end of file rewind(f); // fseek(f, 0L, SEEK_SET); clearerr(f);
f.put(c) // put a single char into output stream
class CPair { feof(f); // Is f at end of file?
ios::app Every output is appended at the end of file f.setf(flag) // sets a flag
T x,y; ferror(f); // Error in f?
If the file already existed it is erased f.setf(flag, mask) // sets a flag w/value
public: ios::trunc
perror(s); // Print char* s and error message
f.width() // returns the current number of characters
Pair(T a, T b){ ios::binary Binary mode clearerr(f); // Clear error code for f
// to be written
x=a; y=b; } remove("filename"); // Delete file, return 0 if OK
ifstream f; // open input file example f.width(num) // sets the number of chars to be written
T GetMax(); rename("old", "new"); // Rename file, return 0 if OK
}; f.open("input.txt", ios::in);
f = tmpfile(); // Create temporary file, mode "wb+"
template <class T> ofstream f; // open for writing in binary
tmpnam(s); // Put a unique file name in char s[L_tmpnam]
T Pair<T>::GetMax() f.open("out.txt", ios::out | ios::binary | ios::app); DYNAMIC MEMORY
{ // implementation of GetMax function Memory can be allocated and deallocated
CLOSING A FILE // allocate memory (C++ only)
STDLIB.H, CSTDLIB (Misc. functions)
T ret; // return a template
f.close(); // close the file with handle f pointer = new type [];
ret = x>y?x:y; // return larger atof(s); // Convert char* s to float,
return ret; int *ptr; // declare a pointer atol(s); // to long,
WRITING TO A FILE (TEXT MODE) ptr = new int; // create a new instance
} The operator << can be used to write to a file. Like cout, a atoi(s); // to int
int main () { ptr = new int [5]; // new array of ints rand(); // Random int 0 to RAND_MAX
stream can be opened to a device. For file writing, the device is
Pair <int> theMax (80, 45); // deallocate memory (C++ only) srand(seed); // reset rand()
not the console, it is the file. cout is replaced with the file delete [] pointer;
cout << theMax.GetMax(); void* p = malloc(n); // Allocate n bytes. Obsolete: use new
return 0; handle. delete ptr; // delete a single int free(p); // Free memory. Obsolete: use delete
} ofstream f; // create file handle delete [] ptr // delete array exit(n); // Kill program, return status n
f.open("output.txt") // open file // allocate memory (C or C++) system(s); // Execute OS command s (system dependent)
f <<"Hello World\n"<<a<<b<<c<<endl; void * malloc (nbytes); // nbytes=size getenv("PATH"); // Environment variable or 0
char *buffer; // declare a buffer // (system dependent)
READING FROM A FILE (TEXT MODE) // allocate 10 bytes to the buffer
FRIEND CLASSES/FUNCTIONS The operator >> can be used to read from a file. It works similar buffer = (char *)malloc(10);
abs(n); labs(ln); // Absolute value as int, long
FRIEND CLASS EXAMPLE to cin. Fields are seperated in the file by spaces. // allocate memory (C or C++) STRING.H, CSTRING
ifstream f; // create file handle // nelements = number elements
f.open("input.txt"); // open file // size = size of each element Character array handling functions
class CSquare; // define CSquare
while (!f.eof()) // end of file test void * malloc (nelements, size);
class CRectangle { Strings are type char[] with a ’\0’ in the last element used.
f >>a>>b>>c; // read into a,b,c int *nums; // declare a buffer
int width, height;
public: // allocate 5 sets of ints strcpy(dst, src); // Copy string. Not bounds checked
I/O STATE FLAGS nums = (char *)calloc(5,sizeof(int));
void convert (CSquare a); Flags are set if errors or other conditions occur. The following strcat(dst, src); // Concatenate to dst.
}; // reallocate memory (C or C++) // Not bounds checked
functions are members of the file object void * realloc (*ptr, size);
class CSquare { // we want to use the strcmp(s1, s2); // Compare, <0 if s1< s2,
handle.bad() /* returns true if a failure occurs in // delete memory (C or C++)
private: // convert function in // 0 if s1==s2,
reading or writing */ void free (*ptr);
int side; // the CSquare class, so // >0 if s1> s2
handle.fail() /* returns true for same cases as bad()
public: // use the friend keyword strncpy(dst, src, n); // Copy up to n chars,
plus if formatting errors occur */
void set_side (int a) { side=a; } // also strncat(), strncmp()
handle.eof() /* returns true if the end of the file
friend class CRectangle;
reached when reading */ ANSI C++ LIBRARY FILES strlen(s); // Length of s not counting \0
}; The following files are part of the ANSI C++ standard and should strchr(s,c); strrchr(s,c); // Address of
handle.good() /* returns false if any of the above
void CRectangle::convert (CSquare a) { work in most compilers. // first/last char c in s or 0
were true */
width = a.side; <algorithm.h> <bitset.h> <deque.h> <exception.h> strstr(s, sub); // Address of first substring in s or 0
height = a.side; STREAM POINTERS <fstream.h> <functional.h> <iomanip.h> <ios.h> /* mem... functions are for any pointer types (void*),
} handle.tellg() // returns pointer to current location <iosfwd.h> <iostream.h> <istream.h> <iterator.h> length n bytes */
// declaration and usage // when reading a file <limits.h> <list.h> <locale.h> <map.h> memmove(dst, src, n); // Copy n bytes from src to dst
CSquare sqr; handle.tellp() // returns pointer to current location <memory.h> <new.h> <numeric.h> <ostream.h> memcmp(s1, s2, n); // Compare n bytes as in strcmp
CRectangle rect; // convert can be // when writing a file <queue.h> <set.h> <sstream.h> <stack.h> memchr(s, c, n); // Find first byte c in s,
sqr.set_side(4); // used by the // seek a position in reading a file <stdexcept.h> <streambuf.h> <string.h> <typeinfo.h> // return address or 0
rect.convert(sqr); // rectangle class handle.seekg(position); <utility.h> <valarray.h> <vector.h> memset(s, c, n); // Set n bytes of s to c

¸ ¸ ¸
[email protected] programmingandmorestuff.blogspot.gr
C++ Reference Natsis Athanasios, Νάτσης Θανάσης cb e a 4/4

CTYPE.H, CCTYPE (Character types) ASSERT.H, CASSERT (Debugging aid) f1.getline(s, n); // Read line into string s[n] vector<int> b(a.begin(), a.end()); // b is copy of a
assert(e); // If e is false, print message and abort ofstream f2("filename"); // Open file for writing vector<T> c(n, x); // c[0]..c[n-1] init to x
isalnum(c); // Is c a letter or digit? #define NDEBUG // (before #include <assert.h>), if (f2) f2 << x; // Write to file T d[10]; vector<T> e(d, d+10); // e is initialized from d
isalpha(c); isdigit(c); // Is c a letter? Digit? // turn off assert
islower(c); isupper(c); // Is c lower case? Upper case? IOMANIP.H, IOMANIP (Output formatting) DEQUE (array/stack/queue)
tolower(c); toupper(c); // Convert c to lower/upper case NEW.H, NEW (Out of memory handler) cout << setw(6) << setprecision(2) << setfill('0') << 3.1; deque<T> is like vector<T>, but also supports:
set_new_handler(handler); // Change behavior // print "003.10" a.push_front(x); // Puts x at a[0], shifts elements
MATH.H, CMATH (Floating point math) // when out of memory // toward back
void handler(void) {throw bad_alloc();} // Default
STRING (Variable sized character array) a.pop_front(); // Removes a[0], shifts toward front
sin(x); cos(x); tan(x); // Trig functions, string s1, s2="hello"; // Create strings
// x (double) is in radians IOSTREAM.H, IOSTREAM (Replaces stdio.h) s1.size(), s2.size(); // Number of characters: 0, 5 UTILITY (Pair)
asin(x); acos(x); atan(x); // Inverses s1 += s2 + ' ' + "world"; // Concatenation pair<string, int> a("hello", 3); // A 2-element struct
cin >> x >> y; // Read words x, y (any type) from stdin
atan2(y, x); // atan(y/x) s1 == "hello world" // Comparison, also <, >, !=, etc. a.first; // "hello"
cout << "x=" << 3 << endl; // Write line to stdout
sinh(x); cosh(x); tanh(x); // Hyperbolic s1[0]; // 'h' a.second; // 3
cerr << x << y << flush; // Write to stderr and flush
exp(x); log(x); // e to the x, log base e s1.substr(m, n); // Substring of size n starting at s1[m]
c = cin.get(); // c = getchar();
log10(x); // log base 10
cin.get(c); // Read char s1.c_str(); // Convert to const char* MAP (associative array)
pow(x, y); sqrt(x); // x to the y, square root getline(cin, s); // Read line ending in '\n' map<string, int> a; // Map from string to int
cin.getline(s, n, '\n'); // Read line into char s[n]
ceil(x); floor(x); // Round up or down (as a double) a["hello"]=3; // Add or replace element a["hello"]
// to '\n' (default)
fabs(x); fmod(x, y); // Absolute value, x mod y
if (cin) // Good state (not EOF)? VECTOR for (map<string, int>::iterator p=a.begin(); \
// To read/write any type T: Variable sized array/stack with built in memory p!=a.end(); ++p)
TIME.H, CTIME (Clock) cout << (*p).first << (*p).second; // Prints hello, 3
istream& operator>>(istream& i, T& x) allocation
clock()/CLOCKS_PER_SEC; // Time in seconds since {i >> ...; x=...; return i;} vector<int> a(10); // a[0]..a[9] int (default size is 0) a.size(); // 1
// program started ostream& operator<<(ostream& o, const T& x) a.size(); // Number of elements (10)
time_t t=time(0); // Absolute time in seconds or {return o << ...;} a.push_back(3); // Increase size to 11, a[10]=3
ALGORITHM
// -1 if unknown a.back()=4; // a[10]=4; A collection of 60 algorithms on sequences
tm* p=gmtime(&t); // 0 if UCT unavailable, else p->tm_X FSTREAM.H, FSTREAM a.pop_back(); // Decrease size by 1 with iterators
// where X is: File I/O works like cin, cout as above a.front(); // a[0]; min(x, y); max(x, y); // Smaller/larger of x, y
// sec, min, hour, mday, mon (0-11), ifstream f1("filename"); // Open text file for reading a[20]=1; // Crash: not bounds checked // (any type defining <)
// year (-1900), wday, yday, isdst if (f1) // Test if open and input available a.at(20)=1; // Like a[20] but throws out_of_range() swap(x, y); // Exchange values of variables x and y
asctime(p); // "Day Mon dd hh:mm:ss yyyy\n" f1 >> x; // Read object from file for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p) sort(a, a+n); // Sort array a[0]..a[n-1] by <
asctime(localtime(&t)); // Same format, local time f1.get(s); // Read char or line *p=0; // Set all elements of a to 0 sort(a.begin(), a.end()); // Sort vector or deque

¸ ¸ ¸
[email protected] programmingandmorestuff.blogspot.gr

You might also like