Anda di halaman 1dari 10

C++ Notes Compiled by tradbow Updated: 2012-04-13

GENERAL
// my first program /* print "Hello World!" 2010-09-09 */ #include <iostream>

Single line (line) comment. May be on the same line as a statement, declaration etc. Multi-line (block) comment.

Preprocessor directives. Each directive must be on it's own line. (iostream contains the standard input-output library) The std namespace containing the standard C++ library. Program execution starts in the main function regardless of where the function is located within the code. This function must exist in every program. A C++ statement. It tells the program to do something. cout is declared in the iostream standard file within the std namespace. All statements must end with a ";" End the program with no error messages.

using namespace std; int main() {}

cout << "Hello World!";

return 0;

IDENTIFIERS Names of variables. Case sensitive. Must begin with a letter or underscore. Can contain only letters, digits, and single underscore characters.

Valid my_Var var1, _var a_and_b

Invalid my___Var 1var a_&_b

KEYWORDS (Reserved Words) asm double auto dynamic_cast bool else break enum case explicit catch export char extern class false const float const_cast for continue friend default goto delete if do inline

int long mutable namespace new operator private protected public register reinterpret_cast return short signed

sizeof static static_cast struct switch template this throw true try typedef typeid typename union

unsigned using virtual void volatile wchar_t while

Alternative representations for some operators under certain conditions. and and_eq bitand bitor or or_eq xor xor_eq

compl

not

not_eq

DATA TYPES Type char wchar_t int float double bool void

Meaning Character or small integer. Wide character. Integer. Floating point number. Double precision floating point number. Boolean value. True or False. Valueless.

signed * *

unsigned * *

long

short

* *

TYPICAL BIT WIDTHS AND RANGES IN A 32-BIT ENVIRONMENT Type Bit Width char 8 unsigned char 8 signed char 8 int 32 unsigned int 32 signed int 32 short int (short) 16 unsigned short int 16 signed short int 16 long int (long) 32 signed long int 32 unsigned long int 32 float 32 double 32 long double 64 bool 8 wchar_t 16 8 bits = 1 byte, 4 bytes = 1 word (register), address = 4 bytes

Typical Range -128 to 127 0 to 255 -128 to 127 -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 -2,147,483,648 to 2,147,483,647 -32,768 to 32,767 0 to 65,535 -32,768 to 32,767 Same as int Same as signed int Same as unsigned int 1.8E-38 to 3.4E+38 2.2E-308 to 1.8E+308 2.2E-308 to 1.8E+308 True or false 0 to 65,535

ARITHMETIC OPERATORS Operator + * / % ++ --

Meaning Addition Subtraction (also unary minus) Multiplication Division Modulus Increment Decrement

CHARACTER ESCAPE SEQUENCES Code \b \f \n \r \t \" \' \\ \v \a \? \N \xN INCREMENT/DECREMENT PRECEDENCE Highest

Meaning Backspace Form feed Newline Carriage return Horizontal tab Double quote Single quote character Backslash Vertical tab Alert ? Octal constant (where N is an octal constant) Hexadecimal constant (where N is a hexadecimal constant)

++ -- (unary minus) */% Lowest + Operators on the same precedence level are evaluated from left to right. Parentheses force a higher precedence level. RELATIONAL OPERATORS (Yield a boolean value.) Operator Meaning > Greater than. >= Greater than or equal to. < Less than. <= Less than or equal to. == Equal to. A single "=" is the assignment operator. != Not equal to. LOGICAL OPERATORS (Yield a boolean value.) Operator Meaning && AND || OR ! NOT TRUTH TABLE p False False True True

q False True True False

p AND q False False True False

p OR q False True True True

NOT p True True False False

RELATIONAL/LOGICAL PRECEDENCE Highest

Lowest

! > >= < <= == != && ||

COMPOUND ASSIGNMENT Expression value += increase; a -= 5; a /= b; price *= units - 1;

Equivalent to value = value + increase; a = a - 5; a = a / b; price = price * (units - 1);

CONDITIONAL OPERATOR (?) Format: condition ? resutl1 : result2 Conditional 7==5 ? 4 : 3 7==5+2 ? 4 : 3 5>3 ? a : b a>b ? a : b

Result 3 4 a whichever is greater

BITWISE OPERATORS Operator & | ^ ~ << >>

ASM Equivalent AND OR XOR NOT SHL SHR

Description Bitwise AND Bitwise Inclusive OR Bitwise Exclusive OR Unary complement (bit inversion) Shift Left. If Lvalue is ostream, writes into the stream. Shift Right. If Rvalue is istream, reads from the stream.

TYPE CASTING
int i; float f = 3.95; i = (int) f; cout << i; 3

// or i = int (f); // notice that the value is truncated not rounded

sizeof()
int a,b,c; a = sizeof (char); b = sizeof (int); c = sizeof (double); cout << "char = " << a << endl; cout << "int = " << b << endl; cout << "double = " << c << endl; char = 1 int = 4 double = 8

OPERATOR PRECEDENCE Level Operator 1 :: () [] . -> ++ -- dynamic_cast static_cast 2 reinterpret_cast const_cast typeid ++ == ~ ! sizeof new delete 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 *& +(type) .* ->* * / % + << >> < > <= >= == != & ^ | && || ?: = *= /= %= += -= >>= <<= &= ^= |= ,

Description scope postfix unary (prefix) indirection and reference (pointers) unary sign operator type casting pointer-to-member multiplicative additive shift relational equality bitwise AND bitwise XOR bitwise OR logical AND logical OR conditional assignment comma

Grouping Left-to-right Left-to-right

Right-to-left Right-to-left Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Right-to-left Right-to-left Left-to-right

STATEMENTS for loop for(initialization; expression; increment) statement; for(initialization; expression; increment) { statement sequence } for(x=0, y=10; x <= y; ++x, --y) cout << x << " " << y <<

'\n';

STATEMENTS (contd) if if(condition) statement; else if(condition) statement; else statement; // optional switch switch(expression) { case constant1: statement sequence break; case constant2: statement sequence break; default; statement sequence }

// optional

while loop while(expression) statement;

do-while loop (will execute at least once) do{statements;} while(condition);

STRING OPERATIONS Operation s.empty() s.size() s[n] s1 + s2 s1 = s2 s1 == s2 !=, <, <=, >, and >=

Result Returns true if s is empty; otherwise returns false. Returns the number of characters in s. Returns the character at position n in s; 0 indexed. Returns a string equal to the concatenation of s1 and s2. Replaces characters in s1 by a copy of s2. Returns true if s1 and s2 are equal; otherwise false. Have their normal meanings.

BITSET OPERATIONS Operation b.any() b.none() b.count() b.size() b[pos] b.test(pos) b.set() b.set(pos) b.reset() b.reset(pos) b.flip() b.flip(pos) b.to_ulong() os << b

Result Is any bit in b on? Are no bits in b on? Number of bits in b that are on. Number of bits in b. Access bit in b at position pos. Is bit in b at position pos on? Turn on all bits in b. Turn on the bit in b at position pos. Turn off all bits in b. Turn off the bit in b at position pos. Change the state of each bit in b. Reverse value of the bit in b at position pos. Returns an unsigned long with the same bits as in b. Prints the bits in b to the stream os.

STANDARD LIBRARY NAMES AND HEADERS Name Header abort <cstdlib> accumulate <numeric> allocator <memory> auto_ptr <memory> back_inserter <iterator> bad_alloc <new> bad_cast <typeinfo> bind2nd <functional> bitset <bitset> boolalpha <iostream> cerr <iostream> cin <iostream> copy <algorithm> count <algorithm> count_if <algorithm> cout <iostream> dec <iostream> deque <deque> endl <iostream> ends <iostream> equal_range <algorithm> exception <exception> fill <algorithm> fill_n <algorithm> find <algorithm> find_end <algorithm> find_first_of <algorithm> fixed <iostream>

Name ios_base isalpha islower ispunct isspace istream istream_iterator istringstream isupper left less_equal list logic_error lower_bound make_pair map max min multimap multiset negate noboolalpha noshowbase noshopoint noskipws notl nounitbuf nouppercase

Header <ios_base> <cctype> <cctype> <cctype> <cctype> <iostream> <iterator> <sstream> <cctype> <iostream> <functional> <list> <stdexcept> <algorithm> <utility> <map> <algorithm> <algorithm> <map> <set> <functional> <iostream> <iostream> <iostream> <iostream> <functional> <iostream> <iostream>

flush for_each front_inserter fstream getline hex ifstream inner_product inserter internal priority_queue prtdiff_t gueue range_error replace replace_copy reverse_iterator right runtime_error scientific set set_difference set_intersection set_union setfill setprecision setw showbase showpoint size_t skipws sort

<iostream> <algorithm> <iterator> <fstream> <string> <iostream> <fstream> <numeric> <iterator> <iostream> <queue> <cstddef> <queue> <stdexcept> <algorithm> <algorithm> <iterator> <iostream> <stdexcept> <iostream> <set> <algorithm> <algorithm> <algorithm> <iomanip> <iomanip> <iomanip> <iostream> <iostream> <cstddef> <iostream> <algorithm>

nth_element oct ofstream ostream ostream_iterator ostringstream out_of_range pair partial_sort plus sqrt stable_sort stack strcmp strcpy string stringstream strlen strncpy terminate tolower toupper type_info unexpected uninitialized_copy unitbuf unigue unigue_copy upper_bound uppercase vector

<algorithm> <iostream> <fstream> <iostream> <iterator> <sstream> <stdexcept> <utility> <algorithm> <functional> <cmath> <algorithm> <stack> <cstring> <cstring> <string> <sstream> <cstring> <cstring> <exception> <cctype> <cctype> <typeinfo> <exception> <memory> <iostream> <algorithm> <algorithm> <algorithm> <iostream> <vector>

string OPERATIONS s.empty() s.size() s[n] s1 + s2 s1 = s2 s1 == s2 !=, <, <=, >, and >=

Returns true if s is empty; otherwise returns false. Returns the number of characters in s. Returns the character at position n in s. (Positions start at 0.) Returns a string equal to the concatenation of s1 and s2. Replaces characters in s1 with a copy of s2. Returns true if s1 and s2 are equal; otherwise returns false. Have their normal meanings.

cctype FUNCTIONS isalnum(c) isalpha(c) iscntrl(c) isdigit(c) isgraph(c) islower(c) isprint(c) ispunct(c) isspace(c) isupper(c) isxdigit(c) tolower(c) toupper(c)

true if c is a letter or a digit true if c is a letter true if c is a control character true if c is a digit true if c is not a space but is printable true if c is a lowercase letter true if c is a printable character true if c is a punctuation character true if c is whitespace true if c is an uppercase letter true if c is a hexadecimal digit If c is an uppercase letter, returns its lowercase equivalent; otherwise returns c unchanged. If c is a lowercase letter, returns its uppercase equivalent; otherwise returns c unchanged.

vector OPERATIONS v.empty() v.size() v.push_back(t) v[n] v1 = v2 v1 == v2 !=, <, <=, >, and >=

Returns true if v is empty; otherwise returns false. Returns the number of elements in v. Adds element with value t to the end of v. Returns the character at position n in v. (Positions start at 0.) Replaces elements in v1 with a copy of elements in v2. Returns true if v1 and v2 are equal; otherwise returns false. Have their normal meanings.

An iterator that cannot write elements: vector<int>::const_iterator An iterator whose value cannot change (cant be iterated): const vector<int>::iterator The three pillars of object-oriented development: encapsulation a self-contained unit inheritance (and reuse) subclass derived from a class polymorphism one name with many forms

Questions to ask before writing a program: What is the problem Im trying to solve? Can this be accomplished without resorting to writing custom software?

Foundation for writing good software: Analysis fully understand the problem Design create a plan for a solution

Anda mungkin juga menyukai