C++ Quick Reference
यह कंटेंट अभी तक आपकी भाषा में उपलब्ध नहीं है।
Preprocessor
Section titled “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, #ifdefLiterals
Section titled “Literals”255, 0377, 0xff // Integers (decimal, octal, hex)2147483647L, 0x7fffffffl // Long (32-bit) integers123.0, 1.23e2 // double (real) numbers'a', '\141', '\x61' // Character (literal, octal, hex)'\n', '\\', '\'', '\"' // Newline, backslash, single quote, doublequote"string\n" // Array of characters ending with newline and\0"hello" "world" // Concatenated stringstrue, false // bool constants 1 and 0Declarations
Section titled “Declarations”int x; // Declare x to be an integer (value undefined)int x=255; // Declare and initialize x to 255short s; long l; // Usually 16 or 32 bit integer (int may be either)char c='a'; // Usually 8 bit characterunsigned char u=255; signed char s=-1; // char might be eitherunsigned long x=0xffffffffL; // short, int, long are signedfloat 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 declarationsint 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 intschar s[]="hello"; // String (6 elements including '\0')int* p; // p is a pointer to (address of) intchar* 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 xenum weekend {SAT,SUN}; // weekend is a type with values SAT and SUNenum weekend day; // day is a variable of type weekendenum weekend {SAT=0,SUN=1}; // Explicit representation as intenum {SAT,SUN} day; // Anonymous enumtypedef String char*; // String s; means char* s;const int c=3; // Constants must be initialized, cannot assign toconst int* p=a; // Contents of p (elements of a) are constantint* const p=a; // p (but not contents) are constantconst int* const p=a; // Both p and its contents are constantconst int& cr=x; // cr cannot be assigned to change xStorage Classes
Section titled “Storage Classes”int x; // Auto (memory exists only while in scope)static int x; // Global lifetime even if local scopeextern int x; // Information only, declared elsewhereStatements
Section titled “Statements”x=y; // Every expression is a statementint 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 aelse 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 switchcontinue; // Jump to bottom of while, do, or for loopreturn x; // Return x from function to callertry { a; }catch (T t) { b; } // If a throws a T, then jump herecatch (...) { c; } // If a throws something else, jump hereFunctions
Section titled “Functions”int f(int x, int); // f is a function taking 2 ints and returning intvoid f(); // f is a procedure taking no argumentsvoid f(int a=0); // f() is equivalent to f(0)f(); // Default return type is intinline f(); // Optimize for speedf() { 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 CFunction 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... } orint 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
Section titled “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 TN::X // Name X defined in namespace N::X // Global name X
t.x // Member x of struct or class tp->x // Member x of struct or class pointed to by pa[i] // i'th element of array af(x,y) // Call to function f with arguments x and yT(x,y) // Object of class T initialized with x and yx++ // Add 1 to x, evaluates to original x (postfix)x-- // Subtract 1 from x, evaluates to original xtypeid(x) // Type of xtypeid(T) // Equals typeid(x) if x is a Tdynamic_cast<T>(x) // Converts x to a T, checked at run timestatic_cast<T>(x) // Converts x to a T, not checkedreinterpret_cast<T>(x) // Interpret bits of x as a Tconst_cast<T>(x) // Converts x to same type T but not const
sizeof x // Number of bytes used to represent object xsizeof(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 objectnew T(x, y) // Address of a T initialized with x, ynew T[x] // Address of allocated n-element array of Tdelete p // Destroy and free object at address pdelete[] p // Destroy and free array of objects at p(T) x // Convert x to T (obsolete, use .._cast<T>(x))
x * y // Multiplyx / 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 thanx <= y // Less than or equal tox > y // Greater thanx >= y // Greater than or equal to
x == y // Equalsx != 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 xx += 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
Section titled “Classes”class T { // A new typeprivate: // Section accessible only to T's member functionsprotected: // Also accessable to classes derived from Tpublic: // 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 Tclass V: private T {}; // Inherited members of T become privateclass W: public T, public U {}; // Multiple inheritanceclass X: public virtual T {}; // Classes derived from X have base T directlyAll 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
Section titled “Templates”template <class T> T f(T t); // Overload f for all typestemplate <class T> class X { // Class with type parameter TX(T t); }; // A constructortemplate <class T> X<T>::X(T t) {} // Definition of constructorX<int> x(3); // An object of type "X of int"template <class T, class U=T, int n=0> // Template with defaultNamespaces
Section titled “Namespaces”namespace N {class T {};} // Hide name TN::T t; // Use name T in namespace Nusing namespace N; // Make T visible without N::C/C++ Standard Library
Section titled “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)
Section titled “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" binaryfclose(f); // Close file ffprintf(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 sprintf("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 fungetc(c, f); // Put back one c to fgetchar(); // 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 EOFgets(s) // fgets(s, INT_MAX, f); no bounds checkfread(s, n, 1, f); // Read n bytes from f to s, return number readfwrite(s, n, 1, f); // Write n bytes of s to f, return number writtenfflush(f); // Force buffered writes to ffseek(f, n, SEEK_SET); // Position binary file f at nftell(f); // Position in f, -1L if errorrewind(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 messageclearerr(f); // Clear error code for fremove("filename"); // Delete file, return 0 if OKrename("old", "new"); // Rename file, return 0 if OKf = tmpfile(); // Create temporary file in mode "wb+"tmpnam(s); // Put a unique file name in char s[L_tmpnam]STDLIB.H, CSTDLIB (Misc. functions)
Section titled “STDLIB.H, CSTDLIB (Misc. functions)”atof(s); atol(s); atoi(s); // Convert char* s to float, long, intrand(), srand(seed); // Random int 0 to RAND_MAX, reset rand()void* p = malloc(n); // Allocate n bytes. Obsolete: use newfree(p); // Free memory. Obsolete: use deleteexit(n); // Kill program, return status nsystem(s); // Execute OS command s (system dependent)getenv("PATH"); // Environment variable or 0 (system dependent)abs(n); labs(ln); // Absolute value as int, longSTRING.H, CSTRING (Character array handling functions)
Section titled “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 checkedstrcat(dst, src); // Concatenate to dst. Not bounds checkedstrcmp(s1, s2); // Compare, <0 if s1<s2, 0 if s1==s2, >0 if s1>s2strncpy(dst, src, n); // Copy up to n chars, also strncat(), strncmp()strlen(s); // Length of s not counting \0strchr(s,c); strrchr(s,c); // Address of first/last char c in s or 0strstr(s, sub); // Address of first substring in s or 0// mem... functions are for any pointer types (void*), length n bytesmemmove(dst, src, n); // Copy n bytes from src to dstmemcmp(s1, s2, n); // Compare n bytes as in strcmpmemchr(s, c, n); // Find first byte c in s, return address or 0memset(s, c, n); // Set n bytes of s to cCTYPE.H, CCTYPE (Character types)
Section titled “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 caseMATH.H, CMATH (Floating point math)
Section titled “MATH.H, CMATH (Floating point math)”sin(x); cos(x); tan(x); // Trig functions, x (double) is in radiansasin(x); acos(x); atan(x); // Inversesatan2(y, x); // atan(y/x)sinh(x); cosh(x); tanh(x); // Hyperbolicexp(x); log(x); log10(x); // e to the x, log base e, log base 10pow(x, y); sqrt(x); // x to the y, square rootceil(x); floor(x); // Round up or down (as a double)fabs(x); fmod(x, y); // Absolute value, x mod yTIME.H, CTIME (Clock)
Section titled “TIME.H, CTIME (Clock)”clock()/CLOCKS_PER_SEC; // Time in seconds since program startedtime_t t=time(0); // Absolute time in seconds or -1 if unknowntm* 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, isdstasctime(p); // "Day Mon dd hh:mm:ss yyyy\n"asctime(localtime(&t)); // Same format, local timeASSERT.H, CASSERT (Debugging aid)
Section titled “ASSERT.H, CASSERT (Debugging aid)”assert(e); // If e is false, print message and abort#define NDEBUG // (before #include <assert.h>), turn off assertNEW.H, NEW (Out of memory handler)
Section titled “NEW.H, NEW (Out of memory handler)”set_new_handler(handler); // Change behavior when out of memoryvoid handler(void) {throw bad_alloc();} // DefaultIOSTREAM.H, IOSTREAM (Replaces stdio.h)
Section titled “IOSTREAM.H, IOSTREAM (Replaces stdio.h)”cin >> x >> y; // Read words x and y (any type) from stdincout << "x=" << 3 << endl; // Write line to stdoutcerr << x << y << flush; // Write to stderr and flushc = cin.get(); // c = getchar();cin.get(c); // Read charcin.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)
Section titled “FSTREAM.H, FSTREAM (File I/O works like cin, cout as above)”ifstream f1("filename"); // Open text file for readingif (f1) // Test if open and input availablef1 >> x; // Read object from filef1.get(s); // Read char or linef1.getline(s, n); // Read line into string s[n]ofstream f2("filename"); // Open file for writingif (f2) f2 << x; // Write to fileIOMANIP.H, IOMANIP (Output formatting)
Section titled “IOMANIP.H, IOMANIP (Output formatting)”cout << setw(6) << setprecision(2) << setfill('0') << 3.1; // print "003.10"STRING (Variable sized character array)
Section titled “STRING (Variable sized character array)”string s1, s2="hello"; // Create stringss1.size(), s2.size(); // Number of characters: 0, 5s1 += s2 + ' ' + "world"; // Concatenations1 == "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)
Section titled “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]=3a.back()=4; // a[10]=4;a.pop_back(); // Decrease size by 1a.front(); // a[0];a[20]=1; // Crash: not bounds checkeda.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 0vector<int> b(a.begin(), a.end()); // b is copy of avector<T> c(n, x); // c[0]..c[n-1] init to xT d[10]; vector<T> e(d, d+10); // e is initialized from dDEQUE (array/stack/queue)
Section titled “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 backa.pop_front(); // Removes a[0], shifts toward frontUTILITY (Pair)
Section titled “UTILITY (Pair)”pair<string, int> a("hello", 3); // A 2-element structa.first; // "hello"a.second; // 3MAP (associative array)
Section titled “MAP (associative array)”map<string, int> a; // Map from string to inta["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, 3a.size(); // 1ALGORITHM (A collection of 60 algorithms on sequences with iterators)
Section titled “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 ysort(a, a+n); // Sort array a[0]..a[n-1] by <sort(a.begin(), a.end()); // Sort vector or deque