This document provides a quick reference for common C++ constructs such as data types, variables, operators, functions, classes and namespaces. It covers basic syntax for declarations, definitions, expressions, statements, comments and preprocessor directives. Constants, literals, storage classes, operators and their precedence are defined. Functions can be declared, defined and called, with parameters, return types and overloading explained.
slide1: the content of functons
slide2: Introduction to function
slide3:function advantages
slide4 -5: types of functions
slide6: elements of user defined functions
slide1: the content of functons
slide2: Introduction to function
slide3:function advantages
slide4 -5: types of functions
slide6: elements of user defined functions
Esoft Metro Campus - Diploma in Web Engineering - (Module VII) Advanced PHP Concepts
(Template - Virtusa Corporate)
Contents:
Arrays
Indexed Arrays
Associative Arrays
Multidimensional arrays
Array Functions
PHP Objects and Classes
Creating an Object
Properties of Objects
Object Methods
Constructors
Inheritance
Method overriding
PHP Strings
printf() Function
String Functions
PHP Date/Time Functions
time() Function
getdate() Function
date() Function
mktime() function
checkdate() function
PHP Form Handling
Collecting form data with PHP
GET vs POST
Data validation against malicious code
Required fields validation
Validating an E-mail address
PHP mail() Function
Using header() function to redirect user
File Upload
Processing the uploaded file
Check if File Already Exists
Limit File Size
Limit File Type
Check if image file is an actual image
Uploading File
Cookies
Sessions
Esoft Metro Campus - Programming with C++
(Template - Virtusa Corporate)
Contents:
Overview of C++ Language
C++ Program Structure
C++ Basic Syntax
Primitive Built-in types in C++
Variable types
typedef Declarations
Enumerated Types
Variable Scope
Constants/Literals
Storage Classes
Operators
Control Constructs
Functions
Math Operations in C++
Arrays
Multi-dimensional Arrays
Strings
C++ Pointers
References
Date and Time
Structures
Basic Input / Output
Classes and Objects
Inheritance
Overloading
Polymorphism
Interfaces
Files and Streams
Exception Handling
Dynamic Memory
Namespaces
Templates
Preprocessor
Multithreading
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
Esoft Metro Campus - Certificate in java basics
(Template - Virtusa Corporate)
Contents:
Structure of a program
Variables & Data types
Constants
Operators
Basic Input/output
Control Structures
Functions
Arrays
Character Sequences
Pointers and Dynamic Memory
Unions
Other Data Types
Input/output with files
Searching
Sorting
Introduction to data structures
Esoft Metro Campus - Diploma in Information Technology - (Module VIII) Programming with Java
(Template - Virtusa Corporate)
Contents:
Introduction to Java
Features of Java
What you can create by Java?
Start Java Programming
Creating First Java Program
Java Virtual Machine
Basic Rules to Remember
Keywords in Java
Comments in Java Programs
Printing Statements
Primitive Data Types in Java
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
If Statement
If… Else Statement
If… Else if… Else Statement
Nested If Statement
While Loop
Do While Loop
For Loop
Reading User Input
Arrays
Two Dimensional Arrays
Objects and Classes
Java Classes
Java Objects
Methods with Return Value
Methods without Return Value
Method Overloading
Variable Types
Inheritance
Method Overriding
Access Modifiers
Packages
GUI Applications in Java
Java Applets
Esoft Metro Campus - Diploma in Web Engineering - (Module VI) Fundamentals of PHP
(Template - Virtusa Corporate)
Contents:
Introduction to PHP
What PHP Can Do?
PHP Environment Setup
What a PHP File is?
PHP Syntax
Comments in PHP
echo and print Statements
PHP Variables
PHP Data Types
Changing Type by settype()
Changing Type by Casting
PHP Constants
Arithmetic Operators
String Operators
Assignment Operators
Comparison Operators
Logical Operators
Operators Precedence
If Statement
If… Else Statement
If… Else if… Else Statement
Switch Statement
The ? Operator
While Loop
Do While Loop
For Loop
break Statement
continue Statement
Functions
User Defined Functions
Functions - Returning values
Default Argument Value
Arguments as Reference
Existence of Functions
Variable Local and Global Scope
The global Keyword
GLOBALS Array
Superglobals
Static Variables
Qcon2011 functions rockpresentation_scalaMichael Stal
This is the part I of the tutorial I planned to give at QCon 2011 on Functional Programming with Scala. It also includes Scala 2.8 as well as upcoming features
Esoft Metro Campus - Diploma in Web Engineering - (Module VII) Advanced PHP Concepts
(Template - Virtusa Corporate)
Contents:
Arrays
Indexed Arrays
Associative Arrays
Multidimensional arrays
Array Functions
PHP Objects and Classes
Creating an Object
Properties of Objects
Object Methods
Constructors
Inheritance
Method overriding
PHP Strings
printf() Function
String Functions
PHP Date/Time Functions
time() Function
getdate() Function
date() Function
mktime() function
checkdate() function
PHP Form Handling
Collecting form data with PHP
GET vs POST
Data validation against malicious code
Required fields validation
Validating an E-mail address
PHP mail() Function
Using header() function to redirect user
File Upload
Processing the uploaded file
Check if File Already Exists
Limit File Size
Limit File Type
Check if image file is an actual image
Uploading File
Cookies
Sessions
Esoft Metro Campus - Programming with C++
(Template - Virtusa Corporate)
Contents:
Overview of C++ Language
C++ Program Structure
C++ Basic Syntax
Primitive Built-in types in C++
Variable types
typedef Declarations
Enumerated Types
Variable Scope
Constants/Literals
Storage Classes
Operators
Control Constructs
Functions
Math Operations in C++
Arrays
Multi-dimensional Arrays
Strings
C++ Pointers
References
Date and Time
Structures
Basic Input / Output
Classes and Objects
Inheritance
Overloading
Polymorphism
Interfaces
Files and Streams
Exception Handling
Dynamic Memory
Namespaces
Templates
Preprocessor
Multithreading
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
Esoft Metro Campus - Certificate in java basics
(Template - Virtusa Corporate)
Contents:
Structure of a program
Variables & Data types
Constants
Operators
Basic Input/output
Control Structures
Functions
Arrays
Character Sequences
Pointers and Dynamic Memory
Unions
Other Data Types
Input/output with files
Searching
Sorting
Introduction to data structures
Esoft Metro Campus - Diploma in Information Technology - (Module VIII) Programming with Java
(Template - Virtusa Corporate)
Contents:
Introduction to Java
Features of Java
What you can create by Java?
Start Java Programming
Creating First Java Program
Java Virtual Machine
Basic Rules to Remember
Keywords in Java
Comments in Java Programs
Printing Statements
Primitive Data Types in Java
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
If Statement
If… Else Statement
If… Else if… Else Statement
Nested If Statement
While Loop
Do While Loop
For Loop
Reading User Input
Arrays
Two Dimensional Arrays
Objects and Classes
Java Classes
Java Objects
Methods with Return Value
Methods without Return Value
Method Overloading
Variable Types
Inheritance
Method Overriding
Access Modifiers
Packages
GUI Applications in Java
Java Applets
Esoft Metro Campus - Diploma in Web Engineering - (Module VI) Fundamentals of PHP
(Template - Virtusa Corporate)
Contents:
Introduction to PHP
What PHP Can Do?
PHP Environment Setup
What a PHP File is?
PHP Syntax
Comments in PHP
echo and print Statements
PHP Variables
PHP Data Types
Changing Type by settype()
Changing Type by Casting
PHP Constants
Arithmetic Operators
String Operators
Assignment Operators
Comparison Operators
Logical Operators
Operators Precedence
If Statement
If… Else Statement
If… Else if… Else Statement
Switch Statement
The ? Operator
While Loop
Do While Loop
For Loop
break Statement
continue Statement
Functions
User Defined Functions
Functions - Returning values
Default Argument Value
Arguments as Reference
Existence of Functions
Variable Local and Global Scope
The global Keyword
GLOBALS Array
Superglobals
Static Variables
Qcon2011 functions rockpresentation_scalaMichael Stal
This is the part I of the tutorial I planned to give at QCon 2011 on Functional Programming with Scala. It also includes Scala 2.8 as well as upcoming features
Write a program that converts an infix expression into an equivalent.pdfmohdjakirfb
Write a program that converts an infix expression into an equivalent postfix expression. The
rules to convert an infix expression into an equivalent postfix expression are as follows (C++):
Initialize pfx to an empty expression and also initialize the stack.
Get the next symbol, sym, from infx.
If sym is an operand, append sym to pfx.
If sym is (, push sym into the stack.
If sym is ), pop and append all of the symbols from the stack until the most recent left
parentheses. Pop and discard the left parentheses.
If sym is an operator:
Pop and append all of the operators from the stack to pfx that are above the most recent left
parentheses and have precedence greater than or equal to sym.
Push sym onto the stack.
After processing infx, some operators might be left in the stack. Pop and append to pfx
everything from the stack.
In this program, you will consider the following (binary) arithmetic operators: +, -, *, and /.
You may assume that the expressions you will process are error free. Design a class that stores
the infix and postfix strings. The class must include the following operations:
getInfix: Stores the infix expression.
showInfix: Outputs the infix expression.
showPostfix: Outputs the postfix expression.
convertToPostfix: Converts the infix expression into a postfix expression. The resulting postfix
expression is stored in pfx.
precedence: Determines the precedence between two operators. If the first operator is of higher
or equal precedence than the second operator, it returns the value true; otherwise, it returns the
value false.
A + B - C;
(A + B ) * C;
(A + B) * (C - D);
A + ((B + C) * (E - F) - G) / (H - I);
A + B * (C + D ) - E / F * G + H;
Infix Expression: A+B-C;
Postfix Expression: AB+C-
Infix Expression: (A+B)*C;
Postfix Expression: AB+C*
Infix Expression: (A+B)*(C-D);
Postfix Expression: AB+CD-*
Infix Expression: A+((B+C)*(E-F)-G)/(H-I);
Postfix Expression: ABC+EF-*G-HI-/+
Infix Expression: A+B*(C+D)-E/F*G+H;
Postfix Expression: ABCD+*+EF/G*-H+
Turn in:
A UML diagram for your class.
The header file for your class.
The implementation file for your class.
The source code for your test program. (C++)
(Below already done code.)
//Header file: myStack.h
#ifndef H_StackType
#define H_StackType
#include
#include
#include \"stackADT.h\"
using namespace std;
template
class stackType: public stackADT
{
public:
const stackType& operator=(const stackType&);
//Overload the assignment operator.
void initializeStack();
//Function to initialize the stack to an empty state.
//Postcondition: stackTop = 0
bool isEmptyStack() const;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
bool isFullStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
void push(const Type& newItem);
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postc.
Rust
Why do you care about Rust? Who has the time to learn all these new languages? It seems like a new one is popping up every other week and this trend is growing at an exponential rate. Good news, a fair number of them are crafted really well and efficiently solve specific problems. Bad news, how do you keep up with all of this, let alone decide which languages to include in your companies technology portfolio.
Despite the challenges of all these new languages, a majority of developers are intrigued about the idea of becoming a polyglot, but don't know where to begin or don't have the time. In my polyglot travels, there is one language of late that is the sure-fire answer to the above questions, Rust.
In this talk I’ll explore the value behind becoming more polyglotic as a developer, how to pick languages to learn, and then dive deep in the the language of Rust. Which in my opinion, is hands down the best up and coming languages to learn.
About the Presenter
Anthony Broad-Crawford has been a developer since the year 2000 with a short side stint as a semi-professional poker player. Since his transition to software development Anthony has...
1. Built 8 patent receiving technologies
2. Founded two global companies
3. Been a CTO (3x), CPO (1x), and CEO (1x)
and is currently the CTO at Fooda where he manages product, user experience, and engineering. Fooda is predominantly web and mobile technology company focused on bringing great & healthy food from the best restaurant's to people while at the office.
Through his career, in production applications Anthony has used Ruby, Java, Jave (Android), Objective-C and Swift, .NET, Erlang, Scala, Node.JS, LISP, Smalltalk, and even assembly, with his recent favorite, Rust . No, not all at the same time in the same application.
Anthony now spends his time building great teams, that leverage great technology, to build great products, but still looks to codes every chance he can get :)
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
Abstract: Chances are you code in a language that's either descended from C, inspired by C, or run in an interpreter that itself is written in C. Still... do you actually know how to code in C? Despite its long-standing position as a sort of "lingua franca", an agreed-upon common language, more and more developers are putting together successful, satisfying careers, without ever learning this seminal language. But what if you have to call into C code from your favorite scripting language, or use APIs like OpenGL that are written to be called from C? Many developers find C very challenging, particularly its manual memory-management and other low-level concerns. In this session, we'll show you why you shouldn't be afraid of C, how you can use the skills you already have from the languages you code in today, and how to master structs, enums, typedefs, malloc(), free(), and the rest of C's sharp edges. Examples will be from the point-of-view of the C-skewing iPhone SDK, but will be designed to be broadly applicable and platform-agnostic.
Fix the following C program in linux. When it is compiled it gives t.pdfmohamednihalshahru
Fix the following C program in linux. When it is compiled it gives the following error: warning
cast to pointer from integer of different size.
Solution
#ifndef endLocation
#define endLocation
#include \"myLinkedlist.h\"
#include \"myString.h\"
class endLocation
can use atoi
int travelCost; // can use atoi
public:
endLocation();
endLocation(String, int, int);
endLocation(endLocation& rhs);
void setName(String);
void setTime(int);
void setCost(int);
String getName();
int getTime();
int getCost();
};
#endif // endLocation
//.cpp implementation
endLocation::endLocation()
endLocation::endLocation(endLocation& rhs)
void endLocation::setName(String inputName)
void endLocation::setTime(int inputTime)
void endLocation::setCost(int inputCost)
String endLocation::getName()
come locationName;
}
int endLocation::getTime()
come travelTime;
}
int endLocation::getCost()
come travelCost;
}
Here is my main
int main( int argc, char* const argv[] )
range of lines here
for(int i = 0; i < num_lines; ++i)dissect and store all strings
size = findIndex(line, \'|\');
strncpy(name, line, size);
index = size + 1;
size = findIndex(line + index, \'|\');
strncpy(time, line + index, size);
index += size + 1;
size = findIndex(line + index, \'|\');
strncpy(cost, line + index, size);
}
in.close();
}
else.
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
••• Exploit the full potential of the CRTP! •••
In this presentation you will learn:
▸ what is the curiously recurring template pattern
▸ the actual cost (memory and time) of virtual functions
▸ how to implement static polymorphism
▸ how to implement expression templates to avoid loops and copies
In C++Add the function min as an abstract function to the classar.pdffantoosh1
In C++:
Add the function min as an abstract function to the classarrayListTypeto return the smallest
element of the list.
Also, write the definition of the function min in the classunorderedArrayListTypeand write a
program to test this function.
arrayListType.h
#ifndef H_arrayListType
#define H_arrayListType
class arrayListType
{
public:
bool isEmpty() const;
//Function to determine whether the list is empty
//Postcondition: Returns true if the list is empty;
// otherwise, returns false.
bool isFull() const;
//Function to determine whether the list is full
//Postcondition: Returns true if the list is full;
// otherwise, returns false.
int listSize() const;
//Function to determine the number of elements in
//the list.
//Postcondition: Returns the value of length.
int maxListSize() const;
//Function to determine the maximum size of the list
//Postcondition: Returns the value of maxSize.
void print() const;
//Function to output the elements of the list
//Postcondition: Elements of the list are output on the
// standard output device.
bool isItemAtEqual(int location, int item) const;
//Function to determine whether item is the same as
//the item in the list at the position specified
//by location.
//Postcondition: Returns true if list[location]
// is the same as item; otherwise,
// returns false.
// If location is out of range, an
// appropriate message is displayed.
virtual void insertAt(int location, int insertItem) = 0;
//Function to insert insertItem in the list at the
//position specified by location.
//Note that this is an abstract function.
//Postcondition: Starting at location, the elements of
// the list are shifted down,
// list[location] = insertItem; length++;
// If the list is full or location is out of
// range, an appropriate message is displayed.
virtual void insertEnd(int insertItem) = 0;
//Function to insert insertItem at the end of
//the list. Note that this is an abstract function.
//Postcondition: list[length] = insertItem; and length++;
// If the list is full, an appropriate
// message is displayed.
void removeAt(int location);
//Function to remove the item from the list at the
//position specified by location
//Postcondition: The list element at list[location] is
// removed and length is decremented by 1.
// If location is out of range, an
// appropriate message is displayed.
void retrieveAt(int location, int& retItem) const;
//Function to retrieve the element from the list at the
//position specified by location
//Postcondition: retItem = list[location]
// If location is out of range, an
// appropriate message is displayed.
virtual void replaceAt(int location, int repItem) = 0;
//Function to replace the elements in the list
//at the position specified by location.
//Note that this is an abstract function.
//Postcondition: list[location] = repItem
// If location is out of range, an
// appropriate message is displayed.
void clearList();
//Function to remove all the elements from the list
//After this operation, the size of t.
Online storefront creation: A business creates an online storefront, which serves as its virtual shop where customers can browse products or services, place orders, and make payments.
Product listing: The business lists its products or services on the online storefront, along with relevant information such as price, product description, and images.
Payment gateway integration: The business integrates a payment gateway into its online storefront, which allows customers to securely make payments online using credit cards, debit cards, or other payment methods.
Order processing: When a customer places an order, the business receives the order information through the online storefront. The business then processes the order, which may involve verifying the availability of the product, preparing the product for shipping, and generating a shipping label.
Shipping and delivery: The business ships the product to the customer's address using a third-party logistics provider or its own delivery service. The customer is provided with tracking information to monitor the status of the shipment.
Customer service: The business provides customer service to address any issues or concerns that the customer may have regarding the product or service.
Example:
Let's take the example of a clothing store that sells its products online through its e-commerce website. The store creates an online storefront and lists its products, which include dresses, shirts, pants, and accessories. Customers can browse the products, select the items they wish to purchase, and make payments online using a payment gateway such as PayPal or Stripe.
Once the order is received, the store processes the order and prepares the product for shipping. The product is then shipped to the customer's address using a logistics provider such as FedEx or UPS. The customer can track the shipment using the tracking information provided by the store.
If the customer is not satisfied with the product, they can contact the store's customer service and initiate a return or exchange. The store handles the return or exchange process and ensures that the customer is satisfied with their purchase.
Un os mic dar ascuțit ne poate pune viața în pericol dacă stăm cu capul într-o poziție necorespunzătoare. De exmplu când ținem telefonul mobil prins între cap și umăr.
1. const int c=3; // Constants must be initialized, cannot assign
C++ QUICK REFERENCE to
const int* p=a; // Contents of p (elements of a) are constant
int* const p=a; // p (but not contents) are constant
PREPROCESSOR const int* const p=a; // Both p and its contents are constant
const int& cr=x; // cr cannot be assigned to change x
// Comment to end of line
/* Multi-line comment */ STORAGE CLASSES
#include <stdio.h> // Insert standard header file
#include "myfile.h" // Insert file in current directory
#define X some text // Replace X with some text int x; // Auto (memory exists only while in scope)
#define F(a,b) a+b // Replace F(1,2) with 1+2 static int x; // Global lifetime even if local scope
#define X extern int x; // Information only, declared elsewhere
some text // Line continuation
#undef X // Remove definition STATEMENTS
#if defined(X) // Condional compilation (#ifdef X)
#else // Optional (#ifndef X or #if !defined(X))
#endif // Required after #if, #ifdef x=y; // Every expression is a statement
int x; // Declarations are statements
; // Empty statement
LITERALS
{ // A block is a single statement
int x; // Scope of x is from declaration to end of
255, 0377, 0xff // Integers (decimal, octal, hex) block
2147483647L, 0x7fffffffl // Long (32-bit) integers a; // In C, declarations must precede statements
123.0, 1.23e2 // double (real) numbers }
'a', '141', 'x61' // Character (literal, octal, hex) if (x) a; // If x is true (not 0), evaluate a
'n', '', ''', '"' // Newline, backslash, single quote, double else if (y) b; // If not x and y (optional, may be repeated)
quote else c; // If not x and not y (optional)
"stringn" // Array of characters ending with newline and
0 while (x) a; // Repeat 0 or more times while x is true
"hello" "world" // Concatenated strings
true, false // bool constants 1 and 0 for (x; y; z) a; // Equivalent to: x; while(y) {a; z;}
do a; while (x); // Equivalent to: a; while(x) a;
DECLARATIONS
switch (x) { // x must be int
case X1: a; // If x == X1 (must be a const), jump here
int x; // Declare x to be an integer (value undefined) case X2: b; // Else if x == X2, jump here
int x=255; // Declare and initialize x to 255 default: c; // Else jump here (optional)
short s; long l; // Usually 16 or 32 bit integer (int may be }
either) break; // Jump out of while, do, or for loop, or switch
char c='a'; // Usually 8 bit character continue; // Jump to bottom of while, do, or for loop
unsigned char u=255; signed char s=-1; // char might be either return x; // Return x from function to caller
unsigned long x=0xffffffffL; // short, int, long are signed try { a; }
float f; double d; // Single or double precision real (never catch (T t) { b; } // If a throws a T, then jump here
unsigned) catch (...) { c; } // If a throws something else, jump here
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]) FUNCTIONS
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 f(int x, int); // f is a function taking 2 ints and returning
int* p; // p is a pointer to (address of) int int
char* s="hello"; // s points to unnamed array containing "hello" void f(); // f is a procedure taking no arguments
void* p=NULL; // Address of untyped memory (NULL is 0) void f(int a=0); // f() is equivalent to f(0)
int& r=x; // r is a reference to (alias of) int x f(); // Default return type is int
enum weekend {SAT,SUN}; // weekend is a type with values SAT and SUN inline f(); // Optimize for speed
enum weekend day; // day is a variable of type weekend f() { statements; } // Function definition (must be global)
enum weekend {SAT=0,SUN=1}; // Explicit representation as int T operator+(T x, T y); // a+b (if type T) calls operator+(a, b)
enum {SAT,SUN} day; // Anonymous enum T operator-(T x); // -a calls function operator-(a)
typedef String char*; // String s; means char* s; T operator++(int); // postfix ++ or -- (parameter ignored)
extern "C" {void f();} // f() was compiled in C
2. 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 x << y // x shifted y bits to left (x * pow(2, y))
declarations and a set of function definitions (possibly in separate files), one of which must be: x >> y // x shifted y bits to right (x / pow(2, y))
x < y // Less than
int main() { statements... } or x <= y // Less than or equal to
int main(int argc, char* argv[]) { statements... } x > y // Greater than
x >= y // Greater than or equal to
argv is an array of argc strings from the command line. By convention, main returns status 0 if successful, 1 or
higher for errors. x == y // Equals
x != y // Not equals
Functions with different parameters may have the same name (overloading). Operators except :: . .* ?: may be x & y // Bitwise and (3 & 6 is 2)
overloaded. Precedence order is not affected. New operators may not be created.
x ^ y // Bitwise exclusive or (3 ^ 6 is 5)
EXPRESSIONS x | y // Bitwise or (3 | 6 is 7)
x && y // x and then y (evaluates y only if x (not 0))
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 x || y // x or else y (evaluates y only if x is false
checks for arrays out of bounds, invalid pointers, etc. (0))
T::X // Name X defined in class T
N::X // Name X defined in namespace N x = y // Assign y to x, returns new value of x
::X // Global name X x += y // x = x + y, also -= *= /= <<= >>= &= |= ^=
t.x // Member x of struct or class t x ? y : z // y if x is true (nonzero), else z
p->x // Member x of struct or class pointed to by p
a[i] // i'th element of array a throw x // Throw exception, aborts if not caught
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 , y // evaluates x and y, returns y (seldom used)
x++ // Add 1 to x, evaluates to original x (postfix)
x-- // Subtract 1 from x, evaluates to original x
typeid(x) // Type of x CLASSES
typeid(T) // Equals typeid(x) if x is a T
dynamic_cast<T>(x) // Converts x to a T, checked at run time class T { // A new type
static_cast<T>(x) // Converts x to a T, not checked private: // Section accessible only to T's member
reinterpret_cast<T>(x) // Interpret bits of x as a T functions
const_cast<T>(x) // Converts x to same type T but not const protected: // Also accessable to classes derived from T
public: // Accessable to all
sizeof x // Number of bytes used to represent object x int x; // Member data
sizeof(T) // Number of bytes to represent type T void f(); // Member function
++x // Add 1 to x, evaluates to new value (prefix) void g() {return;} // Inline member function
--x // Subtract 1 from x, evaluates to new value void h() const; // Does not modify any data members
~x // Bitwise complement of x int operator+(int y); // t+y means t.operator+(y)
!x // true if x is 0, else false (1 or 0 in C) int operator-(); // -t means t.operator-()
-x // Unary minus T(): x(1) {} // Constructor with initialization list
+x // Unary plus (default) T(const T& t): x(t.x) {} // Copy constructor
&x // Address of x T& operator=(const T& t) {x=t.x; return *this; } // Assignment operator
*p // Contents of address p (*&x equals x) ~T(); // Destructor (automatic cleanup routine)
new T // Address of newly allocated T object explicit T(int a); // Allow t=T(3) but not t=3
new T(x, y) // Address of a T initialized with x, y operator int() const {return x;} // Allows int(t)
new T[x] // Address of allocated n-element array of T friend void i(); // Global function i() has private access
delete p // Destroy and free object at address p friend class U; // Members of class U have private access
delete[] p // Destroy and free array of objects at p static int y; // Data shared by all T objects
(T) x // Convert x to T (obsolete, use .._cast<T>(x)) static void l(); // Shared code. May access y but not x
class Z {}; // Nested class T::Z
x * y // Multiply typedef int V; // T::V means int
x / y // Divide (integers round toward 0) };
x % y // Modulo (result has sign of x) void T::f() { // Code for member function f of class T
this->x = x;} // this is address of self (means x=x;)
x + y // Add, or &x[y] int T::y = 2; // Initialization of static member (required)
x - y // Subtract, or number of elements from *x to *y T::l(); // Call to static member
3. struct T { // Equivalent to: class T { public: putc(c, f) // fprintf(f, "%c", c);
virtual void f(); // May be overridden at run time by derived putchar(c); // putc(c, stdout);
class fgets(s, n, f); // Read line into char s[n] from f. NULL if EOF
virtual void g()=0; }; // Must be overridden (pure virtual) gets(s) // fgets(s, INT_MAX, f); no bounds check
class U: public T {}; // Derived class U inherits all members of base fread(s, n, 1, f); // Read n bytes from f to s, return number read
T fwrite(s, n, 1, f); // Write n bytes of s to f, return number
class V: private T {}; // Inherited members of T become private written
class W: public T, public U {}; // Multiple inheritance fflush(f); // Force buffered writes to f
class X: public virtual T {}; // Classes derived from X have base T fseek(f, n, SEEK_SET); // Position binary file f at n
directly 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?
All classes have a default copy constructor, assignment operator, and destructor, which perform the
ferror(f); // Error in f?
corresponding operations on each data member and each base class as shown above. There is also a default no- perror(s); // Print char* s and error message
argument constructor (required to create arrays) if the class has no constructors. Constructors, assignment, and clearerr(f); // Clear error code for f
destructors do not inherit.
remove("filename"); // Delete file, return 0 if OK
rename("old", "new"); // Rename file, return 0 if OK
TEMPLATES f = tmpfile(); // Create temporary file in mode "wb+"
tmpnam(s); // Put a unique file name in char s[L_tmpnam]
template <class T> T f(T t); // Overload f for all types
template <class T> class X { // Class with type parameter T STDLIB.H, CSTDLIB (Misc. functions)
X(T t); }; // A constructor
template <class T> X<T>::X(T t) {} // Definition of constructor atof(s); atol(s); atoi(s);// Convert char* s to float, long, int
X<int> x(3); // An object of type "X of int" rand(), srand(seed); // Random int 0 to RAND_MAX, reset rand()
template <class T, class U=T, int n=0> // Template with default void* p = malloc(n); // Allocate n bytes. Obsolete: use new
parameters free(p); // Free memory. Obsolete: use delete
exit(n); // Kill program, return status n
NAMESPACES 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
namespace N {class T {};} // Hide name T
N::T t; // Use name T in namespace N STRING.H, CSTRING (Character array handling functions)
using namespace N; // Make T visible without N::
Strings are type char[] with a '0' in the last element used.
C/C++ STANDARD LIBRARY 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
Only the most commonly used functions are listed. Header files without .h are in namespace std. File names are strncpy(dst, src, n); // Copy up to n chars, also strncat(), strncmp()
actually lower case. 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
STDIO.H, CSTDIO (Input/output) // mem... functions are for any pointer types (void*), length n bytes
memmove(dst, src, n); // Copy n bytes from src to dst
FILE* f=fopen("filename", "r"); // Open for reading, NULL (0) if error memcmp(s1, s2, n); // Compare n bytes as in strcmp
// Mode may also be "w" (write) "a" append, "a+" update, "rb" binary memchr(s, c, n); // Find first byte c in s, return address or 0
fclose(f); // Close file f memset(s, c, n); // Set n bytes of s to c
fprintf(f, "x=%d", 3); // Print "x=3" Other conversions:
"%5d %u %-8ld" // int width 5, unsigned int, long left just. CTYPE.H, CCTYPE (Character types)
"%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 isalnum(c); // Is c a letter or digit?
"%c %s" // char, char* isalpha(c); isdigit(c); // Is c a letter? Digit?
"%%" // % islower(c); isupper(c); // Is c lower case? Upper case?
sprintf(s, "x=%d", 3); // Print to array of char s tolower(c); toupper(c); // Convert c to lower/upper case
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 MATH.H, CMATH (Floating point math)
ungetc(c, f); // Put back one c to f
getchar(); // getc(stdin); sin(x); cos(x); tan(x); // Trig functions, x (double) is in radians
4. asin(x); acos(x); atan(x);// Inverses STRING (Variable sized character array)
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 string s1, s2="hello"; // Create strings
pow(x, y); sqrt(x); // x to the y, square root s1.size(), s2.size(); // Number of characters: 0, 5
ceil(x); floor(x); // Round up or down (as a double) s1 += s2 + ' ' + "world"; // Concatenation
fabs(x); fmod(x, y); // Absolute value, x mod y s1 == "hello world" // Comparison, also <, >, !=, etc.
s1[0]; // 'h'
s1.substr(m, n); // Substring of size n starting at s1[m]
TIME.H, CTIME (Clock) s1.c_str(); // Convert to const char*
getline(cin, s); // Read line ending in 'n'
clock()/CLOCKS_PER_SEC; // Time in seconds since program started
time_t t=time(0); // Absolute time in seconds or -1 if unknown VECTOR (Variable sized array/stack with built in memory allocation)
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 vector<int> a(10); // a[0]..a[9] are int (default size is 0)
asctime(p); // "Day Mon dd hh:mm:ss yyyyn" a.size(); // Number of elements (10)
asctime(localtime(&t)); // Same format, local time a.push_back(3); // Increase size to 11, a[10]=3
a.back()=4; // a[10]=4;
a.pop_back(); // Decrease size by 1
ASSERT.H, CASSERT (Debugging aid) a.front(); // a[0];
a[20]=1; // Crash: not bounds checked
a.at(20)=1; // Like a[20] but throws out_of_range()
assert(e); // If e is false, print message and abort
for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p)
#define NDEBUG // (before #include <assert.h>), turn off assert *p=0; // Set all elements of a to 0
vector<int> b(a.begin(), a.end()); // b is copy of a
NEW.H, NEW (Out of memory handler) 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
set_new_handler(handler); // Change behavior when out of memory
void handler(void) {throw bad_alloc();} // Default DEQUE (array/stack/queue)
IOSTREAM.H, IOSTREAM (Replaces stdio.h) 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
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 UTILITY (Pair)
c = cin.get(); // c = getchar();
cin.get(c); // Read char
pair<string, int> a("hello", 3); // A 2-element struct
cin.getline(s, n, 'n'); // Read line into char s[n] to 'n' (default) a.first; // "hello"
if (cin) // Good state (not EOF)? a.second; // 3
// 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 << ...;} MAP (associative array)
FSTREAM.H, FSTREAM (File I/O works like cin, cout as above) 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)
ifstream f1("filename"); // Open text file for reading cout << (*p).first << (*p).second; // Prints hello, 3
if (f1) // Test if open and input available a.size(); // 1
f1 >> x; // Read object from file
f1.get(s); // Read char or line
f1.getline(s, n); // Read line into string s[n] ALGORITHM (A collection of 60 algorithms on sequences with iterators)
ofstream f2("filename"); // Open file for writing
if (f2) f2 << x; // Write to file
min(x, y); max(x, y); // Smaller/larger of x, y (any type defining <)
swap(x, y); // Exchange values of variables x and y
IOMANIP.H, IOMANIP (Output formatting) sort(a, a+n); // Sort array a[0]..a[n-1] by <
sort(a.begin(), a.end()); // Sort vector or deque
cout << setw(6) << setprecision(2) << setfill('0') << 3.1; // print
"003.10"