C/C++ Reference

General C/C++

  • Pre-processor commands
  • Operator Precedence
  • Escape Sequences
  • ASCII Chart
  • Data Types
  • Keywords

    Standard C Library:

    • Standard C I/O
    • Standard C String & Character
    • Standard C Math
    • Standard C Time & Date
    • Standard C Memory
    • Other standard C functions

C++

  • C++ I/O
  • C++ Strings

    C++ Standard Template Library

    • C++ Bitsets
    • C++ Double-Ended Queues
    • C++ Lists
    • C++ Maps
    • C++ Multimaps
    • C++ Multisets
    • C++ Priority Queues
    • C++ Queues
    • C++ Sets
    • C++ Stacks
    • C++ Vectors
    • Iterators
All C Functions All C++ Functions

Questions? Check out the FAQ

Last modified on 6/24/2004 by Nate Kohl, with help from a lot of people.


Pre-processor commands

#, ## | manupilate strings
#define | define variables
#error | display an error message
#if, #ifdef, #ifndef, #else, #elif, #endif | conditional operators
#include | insert the contents of another file
#line | set line and file information
#pragma | implementation specific command
#undef | undefine variables
Predefined variables | miscellaneous variables


Pre-processor commands

#,##

The # and ## operators are used with the #define macro. Using # causes the first argument after the # to be returned as a string in quotes. For example, the command

    #define to_string( s ) # s

will make the compiler turn this command

    cout << to_string( Hello World! ) << endl;

into

    cout << "Hello World!" << endl;

Using ## concatenates what's before the ## with what's after it. For example, the command

    #define concatenate( x, y ) x ## y
    ...
    int xy = 10;
    ...

will make the compiler turn

    cout << concatenate( x, y ) << endl;

into

    cout << xy << endl;

which will, of course, display '10' to standard output.

#define

Syntax:
  #define macro-name replacement-string

The #define command is used to make substitutions throughout the file in which it is located. In other words, #define causes the compiler to go through the file, replacing every occurrence of macro-name with replacement-string. The replacement string stops at the end of the line. Here's a typical use for a #define (at least in C):

    #define TRUE 1
    #define FALSE 0
    ...
    int done = 0;
    while( done != TRUE ) {
       ...
    }

Another feature of the #define command is that it can take arguments, making it rather useful as a pseudo-function creator. Consider the following code:

    #define absolute_value( x ) ( ((x) < 0) ? -(x) : (x) )
    ...
    int x = -1;
    while( absolute_value( x ) ) {
       ...
    }

It's generally a good idea to use extra parentheses when using complex macros. Notice that in the above example, the variable "x" is always within it's own set of parentheses. This way, it will be evaluated in whole, before being compared to 0 or multiplied by -1. Also, the entire macro is surrounded by parentheses, to prevent it from being contaminated by other code. If you're not careful, you run the risk of having the compiler misinterpret your code.

#error

Syntax:
  #error message

The #error command simply causes the compiler to stop when it is encountered. When an #error is encountered, the compiler spits out the line number and whatever message is. This command is mostly used for debugging.

#if, #ifdef, #ifndef, #else, #elif, #endif

These commands give simple logic control to the compiler. As a file is being compiled, you can use these commands to cause certain lines of code to be included or not included.

    #if expression

If the value of expression is true, then the code that immediately follows the command will be compiled.

    #ifdef macro

If the "macro" has been defined by a #define statement, then the code immediately following the command will be compiled.

    #ifndef macro

If the "macro" has not been defined by a #define statement, then the code immediately following the command will be compiled.

A few side notes: The command #elif is simply a horribly truncated way to say "elseif" and works like you think it would. You can also throw in a "defined" or "!defined" after an #if to get added functionality.

Here's an example of all these:

    #ifdef DEBUG
      cout << "This is the test version, i=" << i << endl;
    #else
      cout << "This is the production version!" << endl;
    #endif

You might notice how that second example could make debugging a lot easier than inserting a million "cout"s into your code.

#include

Syntax:
  #include <filename>
  #include "filename"

This command slurps in a file and inserts it at the current location. The main difference between the two syntaxes is that if filename is enclosed in angled brackets, then the compiler searches for it somehow. If it is enclosed in quotes, then the compiler doesn't search very hard for the file. While the behavior of these two searches is up to the compiler, usually the angled brackets means to search through the standard library directories, while the quotes indicate a search in the current directory. The spiffy new C++ #include commands don't need to map directly to filenames, at least not for the standard libraries. That's why you can get away with

    #include <iostream>

and not have the compiler choke on you.

#line

Syntax:
  #line line_number "filename"

The #line command is simply used to change the value of the __LINE__ and __FILE__ variables. The filename is optional. The __LINE__ and __FILE__ variables represent the current file and which line is being read. The command

    #line 10 "main.cpp"

changes the current line number to 10, and the current file to "main.cpp".

#pragma

The #pragma command gives the programmer the ability to tell the compiler to do certain things. Since the #pragma command is implementation specific, uses vary from compiler to compiler. One option might be to trace program execution.

#undef

The #undef command undefines a previously defined macro variable, such as a variable defined by a #define.

Predefined Variables

Syntax:
  __LINE__
  __FILE__
  __DATE__
  __TIME__
  _cplusplus
  __STDC__

The following variables can vary by compiler, but generally work:

  • The __LINE__ and __FILE__ variables represent the current line and current file being processed.
  • The __DATE__ variable contains the current date, in the form month/day/year.
  • The __TIME__ variable represents the current time, in the form hour:minute:second.
  • The _cplusplus variable is only defined when compiling a C++ program.
  • The __STDC__ variable is defined when compiling a C program, and may also be defined when compiling C++.


C++ Operator Precedence

The operators at the top of this list are evaluated first.

Precedence | Operators
1 | () | [] | -> | .
 | :: |  |  |
 | ! | ~ | ++ | --
2 | - (unary) | * (dereference)
 | & (address of) | sizeof
3 | ->* | .* |  |
4 | * (multiply) | / | %
5 | + | -
6 | << | >>
7 | < | <= | > | >=
8 | == | !=
9 | & (bitwise AND)
10 | ^
11 | |
12 | &&
13 | ||
14 | ? :
15 | = | += | -= | etc.
16 | ,


Escape Sequences

cppreference.com -> Escape Sequences

Constant Escape Sequences

The following escape sequences can be used to print out special characters.

Escape Sequence | Description
\' | Single quote
\" | Double quote
\\ | Backslash
\0 | Null character
\a | Audible bell
\b | Backspace
\f | Formfeed
\n | Newline
\r | Carriage return
\t | Horizontal tab
\v | Vertical tab
\xnnn | Hexadecimal number (nnn)

An example of this is contained in the following code:

printf( "This\nis\na\ntest\n\nShe said, \"How are you?\"\n" );

which would display

This
is
a
test
She said, "How are you?"


ASCII Chart

The following chart contains ASCII decimal, octal, hexadecimal and character codes for values from 0 to 127.

Decimal | Octal | Hex | Character | Description
0 | 0 | 00 | NUL |
1 | 1 | 01 | SOH | start of header
2 | 2 | 02 | STX | start of text
3 | 3 | 03 | ETX | end of text
4 | 4 | 04 | EOT | end of transmission
5 | 5 | 05 | ENQ | enquiry
6 | 6 | 06 | ACK | acknowledge
7 | 7 | 07 | BEL | bell
8 | 10 | 08 | BS | backspace
9 | 11 | 09 | HT | horizontal tab
10 | 12 | 0A | LF | line feed
11 | 13 | 0B | VT | vertical tab
12 | 14 | 0C | FF | form feed
13 | 15 | 0D | CR | carriage return
14 | 16 | 0E | SO | shift out
15 | 17 | 0F | SI | shift in
16 | 20 | 10 | DLE | data link escape
17 | 21 | 11 | DC1 | no assignment, but usually XON
18 | 22 | 12 | DC2 |
19 | 23 | 13 | DC3 | no assignment, but usually XOFF
20 | 24 | 14 | DC4 |
21 | 25 | 15 | NAK | negative acknowledge
22 | 26 | 16 | SYN | synchronous idle
23 | 27 | 17 | ETB | end of transmission block
24 | 30 | 18 | CAN | cancel
25 | 31 | 19 | EM | end of medium
26 | 32 | 1A | SUB | substitute
27 | 33 | 1B | ESC | escape
28 | 34 | 1C | FS | file seperator
29 | 35 | 1D | GS | group seperator
30 | 36 | 1E | RS | record seperator
31 | 37 | 1F | US | unit seperator
32 | 40 | 20 | SPC | space
33 | 41 | 21 | ! |
34 | 42 | 22 | " |
35 | 43 | 23 | # |
36 | 44 | 24 | $ |
37 | 45 | 25 | % |
38 | 46 | 26 | & |
39 | 47 | 27 | ' |
40 | 50 | 28 | ( |
41 | 51 | 29 | ) |
42 | 52 | 2A | * |
43 | 53 | 2B | + |
44 | 54 | 2C | , |
45 | 55 | 2D | - |
46 | 56 | 2E | . |
47 | 57 | 2F | / |
48 | 60 | 30 | 0 |
49 | 61 | 31 | 1 |
50 | 62 | 32 | 2 |
51 | 63 | 33 | 3 |
52 | 64 | 34 | 4 |
53 | 65 | 35 | 5 |
54 | 66 | 36 | 6 |
55 | 67 | 37 | 7 |
56 | 70 | 38 | 8 |
57 | 71 | 39 | 9 |
58 | 72 | 3A | : |
59 | 73 | 3B | ; |
60 | 74 | 3C | < |
61 | 75 | 3D | = |
62 | 76 | 3E | > |
63 | 77 | 3F | ? |
64 | 100 | 40 | @ |
65 | 101 | 41 | A |
66 | 102 | 42 | B |
67 | 103 | 43 | C |
68 | 104 | 44 | D |
69 | 105 | 45 | E |
70 | 106 | 46 | F |
71 | 107 | 47 | G |
72 | 110 | 48 | H |
73 | 111 | 49 | I |
74 | 112 | 4A | J |
75 | 113 | 4B | K |
76 | 114 | 4C | L |
77 | 115 | 4D | M |
78 | 116 | 4E | N |
79 | 117 | 4F | O |
80 | 120 | 50 | P |
81 | 121 | 51 | Q |
82 | 122 | 52 | R |
83 | 123 | 53 | S |
84 | 124 | 54 | T |
85 | 125 | 55 | U |
86 | 126 | 56 | V |
87 | 127 | 57 | W |
88 | 130 | 58 | X |
89 | 131 | 59 | Y |
90 | 132 | 5A | Z |
91 | 133 | 5B | [ |
92 | 134 | 5C | \ |
93 | 135 | 5D | ] |
94 | 136 | 5E | ^ |
95 | 137 | 5F | _ |
96 | 140 | 60 | ` |
97 | 141 | 61 | a |
98 | 142 | 62 | b |
99 | 143 | 63 | c |
100 | 144 | 64 | d |
101 | 145 | 65 | e |
102 | 146 | 66 | f |
103 | 147 | 67 | g |
104 | 150 | 68 | h |
105 | 151 | 69 | i |
106 | 152 | 6A | j |
107 | 153 | 6B | k |
108 | 154 | 6C | l |
109 | 155 | 6D | m |
110 | 156 | 6E | n |
111 | 157 | 6F | o |
112 | 160 | 70 | p |
113 | 161 | 71 | q |
114 | 162 | 72 | r |
115 | 163 | 73 | s |
116 | 164 | 74 | t |
117 | 165 | 75 | u |
118 | 166 | 76 | v |
119 | 167 | 77 | w |
120 | 170 | 78 | x |
121 | 171 | 79 | y |
122 | 172 | 7A | z |
123 | 173 | 7B | { |
124 | 174 | 7C | | |
125 | 175 | 7D | } |
126 | 176 | 7E | ~ |
127 | 177 | 7F | DEL | delete


C/C++ Data Types

There are five data types for C: void, integer, float, double, and char.

Type | Description
void | associated with no data type
int | integer
float | floating-point number
double | double precision floating-point number
char | character

C++ defines two more: bool and wchar_t.

Type | Description
bool | Boolean value, true or false
wchar_t | wide character

Type Modifiers

Several of these types can be modified using signed, unsigned, short, and long. When one of these type modifiers is used by itself, a data type of int is assumed. A complete list of possible data types follows:

bool
char
unsigned char
signed char
int
unsigned int
signed int
short int
unsigned short int
signed short int
long int
signed long int
unsigned long int
float
double
long double
wchar_t

Type Sizes and Ranges

The size and range of any data type is compiler and architecture dependent. The "cfloat" (or "float.h") header file often defines minimum and maximum values for the various data types. You can use the sizeof operator to determine the size of any data type, in bytes. However, many architectures implement data types of a standard size. ints and floats are often 32-bit, chars 8-bit, and doubles are usually 64-bit. bools are often implemented as 8-bit data types.


C/C++ Keywords

asm | insert an assembly instruction
auto | declare a local variable
bool | declare a boolean variable
break | break out of a loop
case | part of a switch statement
catch | handles thrown exceptions
char | declare a character variable
class | declare a class
const | declare immutable data
const_cast | cast from const variables
continue | bypass iterations of a loop
default | default handler in a case statement
delete | free memory
do | looping construct
double | declare a double precision floating-point variable
dynamic_cast | perform runtime casts
else | alternate case for an if statement
enum | create enumeration types
explicit | only use constructors when they exactly match
extern | tell the compiler about variables defined elsewhere
false | the boolean value of false
float | declare a floating-point variable
for | looping construct
friend | grant non-member function access to private data
goto | jump to a different part of the program
if | execute code based off of the result of a test
inline | expand a call to a function rather than calling that function
int | declare a integer variable
long | declare a long integer variable
mutable | override a const variable
namespace | partition the global namespace by defining a scope
new | allocate dynamic memory for a new variable
operator | create overloaded operator functions
private | declare private members of a class
protected | declare protected members of a class
public | declare public members of a class
register | request that a variable be optimized for speed
reinterpret_cast | change the type of a variable
return | return from a function
short | declare a short integer variable
signed | modify variable type declarations
sizeof | return the size of a variable or type
static | create permanent storage for a variable
static_cast | perform a nonpolymorphic cast
struct | create a new structure
switch | execute code based off of different possible values for a variable
template | create generic functions
this | a pointer to the current object
throw | throws an exception
true | the boolean value of true
try | execute code that can throw an exception
typedef | create a new type name from an existing type
typeid | describes an object
typename | declare a class or undefined type
union | a structure that assigns multiple variables to the same memory location
unsigned | declare an unsigned integer variable
using | used to import a namespace
virtual | create a function that can be overridden by a derived class
void | declare functions or data with no associated data type
volatile | warn the compiler about variables that can be modified unexpectedly
wchar_t | declare a wide-character variable
while | looping mechanism


C/C++ Keywords

asm

Syntax:
  asm( "instruction" );

The asm command allows you to insert assembly language commands directly into your code. Various different compilers allow differing forms for this command, such as

    asm {
      instruction-sequence
    }

or

    asm( instruction );

auto

The keyword auto is used to declare local variables, and is purely optional.

bool

The keyword bool is used to declare Boolean logic variables; that is, variables which can be either true or false. An example:

    bool done = false;
    while( !done ) {
    ...
    }

Also see the data types page.

break

The break keyword is used to break out of a do, for, or while loop. It is also used to finish each clause of a switch statement, keeping the program from "falling through" to the next case in the code. An example:

    while( x < 100 ) {
      if( x < 0 )
        break;
      cout << x << endl;
      x++;
    }

A given break statement will break out of only the closest loop, no further. If you have a triply-nested for loop, for example, you might want to include extra logic or a goto statement to break out of the loop.

case

A single test in the switch statement.

Related topics:
default, switch

catch

The catch statement handles exceptions generated by the throw statement.

Related topics:
throw, try

char

The char keyword is used to declare character variables. Also see the data types page.

class

Syntax:
  class class-name : inheritance-list {
    private-members-list;
    protected:
      protected-members-list;
    public:
      public-members-list;
  } object-list;

The class keyword allows you to create new classes. class-name is the name of the class that you wish to create, and inheritance-list is an optional list of classes inherited by the new class. Members of the class are private by default, unless listed under either the protected or public labels. object-list can be used to immediately instantiate one or more instances of the class, and is also optional. For example:

    class Date {
      int Day;
      int Month;
      int Year;
    public:
      void display();
    };
Related topics:
struct, union

const

The const keyword can be used to tell the compiler that a certain variable should not be modified once it has been initialized.

Related topics:
const_cast

const_cast

Syntax:
  const_cast<type> (object);

The const_cast keyword can be used to remove the "const-ness" of some datum. The target data type must be the same as the source type, except (of course) that the target type doesn't have to be const.

Related topics:
dynamic_cast, reinterpret_cast, static_cast

continue

The continue statement can be used to bypass iterations of a given loop. For example, the following code will display all of the numbers between 0 and 20 except 10:

    for( int i = 0; i < 21; i++ ) {
      if( i == 10 ) {
        continue;
      }
      cout << i << " ";
    }
Related topics:
break, do, for, while

default

A default case in the switch statement.

Related topics:
case, switch

delete

Syntax:
  delete p;
  delete[] pArray;

The delete operator frees the memory pointed to by p. The argument should have been previously allocated by a call to new. The second form of delete should be used to delete an array.

Related topics:
new

do

Syntax:
  do {
    statement-list;
  } while( condition );

The do construct evaluates the given statement-list repeatedly, until condition becomes false. Note that every do loop will evaluate its statement list at least once, because the terminating condition is tested at the end of the loop.

Related topics:
for, while

double

The double keyword is used to declare double precision floating-point variables. Also see the data types page.

dynamic_cast

Syntax:
  dynamic_cast<type> (object);

The dynamic_cast keyword casts a datum from one type to another, performing a runtime check to ensure the validity of the cast. If you attempt to cast between incompatible types, the result of the cast will be NULL.

Related topics:
const_cast, reinterpret_cast, static_cast

else

The else keyword is used as an alternative case for the if statement.

enum

Syntax:
  enum name {name-list} var-list;

The enum keyword is used to create an enumerated type named name that consists of the elements in name-list. The var-list argument is optional. For example:

    enum color {red, orange, yellow, green, blue, indigo, violet};
    color c1 = indigo;
    if( c1 == indigo ) {
      cout << "c1 is indigo" << endl;
    }

explicit

When a constructor is specified as explicit, no automatic conversion will be used with that constructor --it will only be used when an initialization exactly matches a call to that constructor.

extern

The extern keyword is used to inform the compiler about variables declared outside of the current scope. Variables described by extern statements will not have any space allocated for them, as they should be properly defined elsewhere.

Extern statements are frequently used to allow data to span the scope of multiple files.

false

The Boolean value of "false".

Related topics:
bool, true

float

The float keyword is used to declare floating-point variables. Also see the data types page.

for

Syntax:
  for( initialization; test-condition; increment ) {
    statement-list;
  }

The for construct is a general looping mechanism consisting of 4 parts:

  1. the initialization, which consists of 0 or more comma-delimited variable initialization statements
  2. the test-condition, which is evaluated to determine if the execution of the for loop will continue
  3. the increment, which consists of 0 or more comma-delimited statements that increment variables
  4. and the statement-list, which consists of 0 or more statements that will be executed each time the loop is executed.
For example:

    for( int i = 0; i < 10; i++ ) {
      cout << "i is " << i << endl;
    }
    int j, k;
    for( j = 0, k = 10;
         j < k;
         j++, k-- ) {
      cout << "j is " << j << " and k is " << k << endl;
    }
    for( ; ; ) {
      // loop forever!
    }
Related topics:
do, while

friend

The friend keyword allows classes or functions not normally associated with a given class to have access to the private data of that class.

goto

Syntax:
  goto labelA;
  ...
  labelA:

The goto statement causes the current thread of execution to jump to the specified label. While the use of the goto statement is generally considered harmful, it can occasionally be useful. For example, it may be cleaner to use a goto to break out of a deeply-nested for loop, compared to the space and time that extra break logic would consume.

Related topics:
break

if

Syntax:
  if( conditionA ) {
    statement-listA;
  }
  else if( conditionB ) {
    statement-listB;
  }
  ...
  else {
    statement-listN;
  }

The if construct is a branching mechanism that allows different code to execute under different conditions. The conditions are evaluated in order, and the statement-list of the first condition to evaluate to true is executed. If no conditions evaluate to true and an else statement is present, then the statement list within the else block will be executed. All of the else blocks are optional.

Related topics:
else, for, while

inline

Syntax:
  inline int functionA( int i ) {
    ...
  }

The inline keyword requests that the compiler expand a given function in place, as opposed to inserting a call to that function. Functions that contain static data, loops, switches, or recursive calls cannot be inlined. When a function declaration is included in a class declaration, the compiler should try to automatically inline that function.

int

The int keyword is used to declare integer variables. Also see the data types page.

long

The long keyword is a data type modifier that is used to declare long integer variables. See the data types page.

Related topics:
short

mutable

The mutable keyword overrides any enclosing const statement. A mutable member of a const object can be modified.

namespace

Syntax:
  namespace name {
    declaration-list;
  }

The namespace keyword allows you to create a new scope. The name is optional, and can be omitted to create an unnamed namespace. Once you create a namespace, you'll have to refer to it explicitly or use the using keyword. For example:

    namespace CartoonNameSpace {
      int HomersAge;
      void incrementHomersAge() {
        HomersAge++;
      }
    }
    int main() {
      ...
      CartoonNameSpace::HomersAge = 39;
      CartoonNameSpace::incrementHomersAge();
      cout << CartoonNameSpace::HomersAge << endl;
      ...
    }

new

Syntax:
  pointer = new type;
  pointer = new type( initializer );
  pointer = new type[size];

The new operator allocates a new chunk of memory to hold a variable of type type and returns a pointer to that memory. An optional initializer can be used to initialize the memory. Allocating arrays can be accomplished by providing a size parameter in brackets.

Related topics:
delete

operator

Syntax:
  return-type class-name::operator#(parameter-list) {
    ...
  }
  return-type operator#(parameter-list) {
    ...
  }

The operator keyword is used to overload operators. The sharp sign (#) listed above in the syntax description represents the operator which will be overloaded. If part of a class, the class-name should be specified. For unary operators, parameter-list should be empty, and for binary operators, parameter-list should contain the operand on the right side of the operator (the operand on the left side is passed as this).

For the non-member operator overload function, the operand on the left side should be passed as the first parameter and the operand on the right side should be passed as the second parameter.

You cannot overload the #, ##, ., :, .*, or ? tokens.

private

Private data of a class can only be accessed by members of that class, except when friend is used. The private keyword can also be used to inherit a base class privately, which causes all public and protected members of the base class to become private members of the derived class.

Related topics:
protected, public

protected

Protected data are private to their own class but can be inherited by derived classes. The protected keyword can also be used as an inheritance specifier, which causes all public and protected members of the base class to become protected members of the derived class.

Related topics:
private, public

public

Public data in a class are accessible to everyone. The public keyword can also be used as an inheritance specifier, which causes all public and protected members of the base class to become public and protected members of the derived class.

Related topics:
private, protected

register

The register keyword requests that a variable be optimized for speed, and fell out of common use when computers became better at most code optimizations than humans.

Related topics:
auto

reinterpret_cast

Syntax:
  reinterpret_cast<type> (object);

The reinterpret_cast operator changes one data type into another. It should be used to cast between incompatible pointer types.

Related topics:
const_cast, dynamic_cast, static_cast

return

Syntax:
  return;
  return( value );

The return statement causes execution to jump from the current function to whatever function called the current function. An optional value can be returned. A function may have more than one return statement.

short

The short keyword is a data type modifier that is used to declare short integer variables. See the data types page.

Related topics:
long

signed

The signed keyword is a data type modifier that is usually used to declare signed char variables. See the data types page.

Related topics:
unsigned

sizeof

The sizeof operator is a compile-time operator that returns the size, in bytes, of the argument passed to it.

static

The static data type modifier is used to create permanent storage for variables. Static variables keep their value between function calls. When used in a class, all instantiations of that class share one copy of the variable.

static_cast

Syntax:
  static_cast<type> (object);

The static_cast keyword can be used for any normal conversion between types. No runtime checks are performed.

Related topics:
const_cast, dynamic_cast, reinterpret_cast

struct

Syntax:
  struct struct-name : inheritance-list {
    public-members-list;
    protected:
      protected-members-list;
    private:
      private-members-list;
  } object-list;

Structs are like classes, except that by default members of a struct are public rather than private. In C, structs can only contain data and are not permitted to have inheritance lists. For example:

    struct Date {
      int Day;
      int Month;
      int Year;
    };
Related topics:
class, union

switch

Syntax:
  switch( expression ) {
    case A:
      statement list;
      break;
    case B:
      statement list;
      break;
    ...
    case N:
      statement list;
      break;
    default:
      statement list;
      break;
  }

The switch statement allows you to test an expression for many values, and is commonly used as a replacement for multiple if()...else if()...else if()... statements. break statements are required between each case statement, otherwise execution will "fall-through" to the next case statement. The default case is optional. If provided, it will match any case not explicitly covered by the preceding cases in the switch statement. For example:

    char keystroke = getch();
    switch( keystroke ) {
      case 'a':
      case 'b':
      case 'c':
      case 'd':
        KeyABCDPressed();
        break;
      case 'e':
        KeyEPressed();
        break;
      default:
        UnknownKeyPressed();
        break;
    }
Related topics:
break, case, default, if

template

Syntax:
  template <class data-type> return-type name( parameter-list ) {
    statement-list;
  }

Templates are used to create generic functions and can operate on data without knowing the nature of that data. They accomplish this by using a placeholder data-type for which many other data types can be substituted. For example:

    template<class X> void genericSwap( X &a, X &b ) {
      X tmp;

      tmp = a;
      a = b;
      b = tmp;
    }
    int main(void) {
      ...
      int num1 = 5;
      int num2 = 21;
      cout << "Before, num1 is " << num1 << " and num2 is " << num2 << endl;
      genericSwap( num1, num2 );
      cout << "After, num1 is " << num1 << " and num2 is " << num2 << endl;
      char c1 = 'a';
      char c2 = 'z';
      cout << "Before, c1 is " << c1 << " and c2 is " << c2 << endl;
      genericSwap( c1, c2 );
      cout << "After, c1 is " << c1 << " and c2 is " << c2 << endl;
      ...
      return( 0 );
    }

this

The this keyword is a pointer to the current object. All member functions of a class have a this pointer.

Related topics:
class

throw

Syntax:
  try {
    statement list;
  }
  catch( typeA arg ) {
    statement list;
  }
  catch( typeB arg ) {
    statement list;
  }
  ...
  catch( typeN arg ) {
    statement list;
  }

The throw statement is part of the C++ mechanism for exception handling. Together with the try and catch statements, the C++ exception handling system gives programmers an elegant mechanism for error recovery. You will generally use a try block to execute potentially error-prone code. Somewhere in this code, a throw statement can be executed, which will cause execution to jump out of the try block and into one of the catch blocks. For example:

    try {
      cout << "Before throwing exception" << endl;
      throw 42;
      cout << "Shouldn't ever see this" << endl;
    }
    catch( int error ) {
      cout << "Error: caught exception " << error << endl;
    }
Related topics:
catch, try

true

The Boolean value of "true".

Related topics:
bool, false

try

The try statement attempts to execute exception-generating code. See the throw statement for more details.

Related topics:
catch, throw

typedef

Syntax:
  typedef existing-type new-type;

The typedef keyword allows you to create a new type from an existing type.

typeid

Syntax:
  typeid( object );

The typeid operator returns a reference to a type_info object that describes object.

typename

The typename keyword can be used to describe an undefined type or in place of the class keyword in a template declaration.

union

Syntax:
  union union-name {
    public-members-list;
    private:
      private-members-list;
  } object-list;

Unions are like classes, except that all members of a union share the same memory location and are by default public rather than private. For example:

    union Data {
      int i;
      char c;
    };
Related topics:
class, struct

unsigned

The unsigned keyword is a data type modifier that is usually used to declare unsigned int variables. See the data types page.

Related topics:
signed

using

The using keyword is used to import a namespace into the current scope.

Related topics:
namespace

virtual

Syntax:
  virtual return-type name( parameter-list );
  virtual return-type name( parameter-list ) = 0;

The virtual keyword can be used to create virtual functions, which can be overridden by derived classes.

  • A virtual function indicates that a function can be overridden in a subclass, and that the overridden function will actually be used.
  • When a base object pointer points to a derived object that contains a virual function, the decision about which version of that function to call is based on the type of object pointed to by the pointer, and this process happens at runtime.
  • A base object can point to different derived objects and have different versions of the virual function run.

If the function is specified as a pure virtual function (denoted by the = 0), it must be overridden by a derived class.

volatile

The volatile keyword is an implementation-dependent modifier, used when declaring variables, which prevents the compiler from optimizing those variables. Volatile should be used with variables whose value can change in unexpected ways (i.e. through an interrupt), which could conflict with optimizations that the compiler might perform.

void

The void keyword is used to denote functions that return no value, or generic variables which can point to any type of data. Void can also be used to declare an empty parameter list. Also see the data types page.

wchar_t

The keyword wchar_t is used to declare wide character variables. Also see the data types page.

while

Syntax:
  while( condition ) {
    statement-list;
  }

The while keyword is used as a looping construct that will evaluate the statement-list as long as condition is true. Note that if the condition starts off as false, the statement-list will never be executed. (You can use a do loop to guarantee that the statement-list will be executed at least once.) For example:

    bool done = false;
    while( !done ) {
      ProcessData();
      if( StopLooping() ) {
        done = true;
      }
    }
Related topics:
do, for


Standard C I/O

clearerr() | clears errors
fclose() | close a file
feof() | true if at the end-of-file
ferror() | checks for a file error
fflush() | writes the contents of the output buffer
fgetc() | get a character from a stream
fgetpos() | get the file position indicator
fgets() | get a string of characters from a stream
fopen() | open a file
fprintf() | print formatted output to a file
fputc() | write a character to a file
fputs() | write a string to a file
fread() | read from a file
freopen() | open an existing stream with a different name
fscanf() | read formatted input from a file
fseek() | move to a specific location in a file
fsetpos() | move to a specific location in a file
ftell() | returns the current file position indicator
fwrite() | write to a file
getc() | read a character from a file
getchar() | read a character from STDIN
gets() | read a string from STDIN
perror() | displays a string version of the current error to STDERR
printf() | write formatted output to STDOUT
putc() | write a character to a stream
putchar() | write a character to STDOUT
puts() | write a string to STDOUT
remove() | erase a file
rename() | rename a file
rewind() | move the file position indicator to the beginning of a file
scanf() | read formatted input from STDIN
setbuf() | set the buffer for a specific stream
setvbuf() | set the buffer and size for a specific stream
sprintf() | write formatted output to a buffer
sscanf() | read formatted input from a buffer
tmpfile() | return a pointer to a temporary file
tmpnam() | return a unique filename
ungetc() | puts a character back into a stream
vprintf, vfprintf, vsprintf | write formatted output with variable argument lists


Standard C I/O

clearerr

Syntax:
  #include <stdio.h>
  void clearerr( FILE *stream );

The clearerr function resets the error flags and EOF indicator for the given stream. When an error occurs, you can use perror() to figure out which error actually occurred.

Related topics:
feof(), ferror(), and perror().

fclose

Syntax:
  #include <stdio.h>
  int fclose( FILE *stream );

The function fclose() closes the given file stream, deallocating any buffers associated with that stream. fclose() returns 0 upon success, and EOF otherwise.

Related topics:
fopen(), freopen(), and fflush().

feof

Syntax:
  #include <stdio.h>
  int feof( FILE *stream );

The function feof() returns a nonzero value if the end of the given file stream has been reached.

Related topics:
clearerr(), ferror(), perror(), putc(), and getc().

ferror

Syntax:
  #include <stdio.h>
  int ferror( FILE *stream );

The ferror() function looks for errors with stream, returning zero if no errors have occured, and non-zero if there is an error. In case of an error, use perror() to determine which error has occured.

Related topics:
clearerr(), feof(), perror(),

fflush

Syntax:
  #include <stdio.h>
  int fflush( FILE *stream );

If the given file stream is an output stream, then fflush() causes the output buffer to be written to the file. If the given stream is of the input type, then fflush() causes the input buffer to be cleared. fflush() is useful when debugging, if a program segfaults before it has a chance to write output to the screen. Calling fflush( STDOUT ) directly after debugging output will ensure that your output is displayed at the correct time.

    printf( "Before first call\n" );
    fflush( STDOUT );
    shady_function();
    printf( "Before second call\n" );
    fflush( STDOUT );
    dangerous_dereference();
Related topics:
fclose(), fopen(), fread(), fwrite(), getc(), and putc().

fgetc

Syntax:
  #include <stdio.h>
  int fgetc( FILE *stream );

The fgetc() function returns the next character from stream, or EOF if the end of file is reached or if there is an error.

Related topics:
fputc(), getc(), putc(), and fopen().

fgetpos

Syntax:
  #include <stdio.h>
  int fgetpos( FILE *stream, fpos_t *position );

The fgetpos() function stores the file position indicator of the given file stream in the given position variable. The position variable is of type fpos_t (which is defined in stdio.h) and is an object that can hold every possible position in a FILE. fgetpos() returns zero upon success, and a non-zero value upon failure.

Related topics:
fsetpos(), fseek(), and ftell().

fgets

Syntax:
  #include <stdio.h>
  char *fgets( char *str, int num, FILE *stream );

The function fgets() reads up to num - 1 characters from the given file stream and dumps them into str. fgets() will stop when it reaches the end of a line, in which case str will be terminated with a newline. If fgets() reaches num - 1 characters or encounters the EOF, str will be null-terminated. fgets() returns str on success, and NULL on an error.

fopen

Syntax:
  #include <stdio.h>
  FILE *fopen( const char *fname, const char *mode );

The fopen() function opens a file indicated by fname and returns a stream associated with that file. If there is an error, fopen() returns NULL. mode is used to determine how the file will be treated (i.e. for input, output, etc)

Mode | Meaning
"r" | Open a text file for reading
"w" | Create a text file for writing
"a" | Append to a text file
"rb" | Open a binary file for reading
"wb" | Create a binary file for writing
"ab" | Append to a binary file
"r+" | Open a text file for read/write
"w+" | Create a text file for read/write
"a+" | Open a text file for read/write
"rb+" | Open a binary file for read/write
"wb+" | Create a binary file for read/write
"ab+" | Open a binary file for read/write

An example:

    char ch;
    FILE *input = fopen( "stuff", "r" );
    ch = getc( input );

fprintf

Syntax:
  #include <stdio.h>
  int fprintf( FILE *stream, const char *format, ... );

The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf() as far as the format goes. The return value of fprintf() is the number of characters outputted, or a negative number if an error occurs. An example:

    char name[20] = "Mary";
    FILE *out;
    out = fopen( "output.txt", "w" );
    if( out != NULL )
      fprintf( out, "Hello %s\n", name );
Related topics:
printf() and fscanf().

fputc

Syntax:
  #include <stdio.h>
  int fputc( int ch, FILE *stream );

The function fputc() writes the given character ch to the given output stream. The return value is the character, unless there is an error, in which case the return value is EOF.

Related topics:
fgetc(), fopen(), fprintf(), fread(), and fwrite().

fputs

Syntax:
  #include <stdio.h>
  int fputs( const char *str, FILE *stream );

The fputs() function writes an array of characters pointed to by str to the given output stream. The return value is non-negative on success, and EOF on failure.

Related topics:
fgets(), gets(), puts(), fprintf(), and fscanf().

fread

Syntax:
  #include <stdio.h>
  int fread( void *buffer, size_t size, size_t num, FILE *stream );

The function fread() reads num number of objects (where each object is size bytes) and places them into the array pointed to by buffer. The data comes from the given input stream. The return value of the function is the number of things read...use feof() or ferror() to figure out if an error occurs.

Related topics:
fwrite(), fopen(), fscanf(), fgetc(), and getc().

freopen

Syntax:
  #include <stdio.h>
  FILE *freopen( const char *fname, const char *mode, FILE *stream );

The freopen() function is used to reassign an existing stream to a different file and mode. After a call to this function, the given file stream will refer to fname with access given by mode. The return value of freopen() is the new stream, or NULL if there is an error.

Related topics:
fopen() and fclose().

fscanf

Syntax:
  #include <stdio.h>
  int fscanf( FILE *stream, const char *format, ... );

The function fscanf() reads data from the given file stream in a manner exactly like scanf(). The return value of fscanf() is the number of variables that are actually assigned values, or EOF if no assignments could be made.

Related topics:
scanf() and fprintf().

fseek

Syntax:
  #include <stdio.h>
  int fseek( FILE *stream, long offset, int origin );

The function fseek() sets the file position data for the given stream. The origin value should have one of the following values (defined in stdio.h):

fseek() returns zero upon success, non-zero on failure. You can use fseek() to move beyond a file, but not before the beginning. Using fseek() clears the EOF flag associated with that stream.

Related topics:
ftell(), rewind(), fopen(), fgetpos(), and fsetpos().

fsetpos

Syntax:
Name | Explanation
SEEK_SET | Seek from the start of the file
SEEK_CUR | Seek from the current location
SEEK_END | Seek from the end of the file
  #include <stdio.h>
  int fsetpos( FILE *stream, const fpos_t *position );

The fsetpos() function moves the file position indicator for the given stream to a location specified by the position object. fpos_t is defined in stdio.h. The return value for fsetpos() is zero upon success, non-zero on failure.

Related topics:
fgetpos(), fseek(), and ftell().

ftell

Syntax:
  #include <stdio.h>
  long ftell( FILE *stream );

The ftell() function returns the current file position for stream, or -1 if an error occurs.

Related topics:
fseek() and fgetpos().

fwrite

Syntax:
  #include <stdio.h>
  int fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

The fwrite() function writes, from the array buffer, count objects of size size to stream. The return value is the number of objects written.

Related topics:
fread(), fscanf(), getc(), and fgetc().

getc

Syntax:
  #include <stdio.h>
  int getc( FILE *stream );

The getc() function returns the next character from stream, or EOF if the end of file is reached. getc() is identical to fgetc(). For example:

    char ch;
    FILE *input = fopen( "stuff", "r" );

    ch = getc( input );
    while( ch != EOF ) {
      printf( "%c", ch );
      ch = getc( input );
    }
Related topics:
fputc(), fgetc(), putc(), and fopen().

getchar

Syntax:
  #include <stdio.h>
  int getchar( void );

The getchar() function returns the next character from STDIN, or EOF if the end of file is reached.

Related topics:
fputc(), fgetc(), putc(), and fopen().

gets

Syntax:
  #include <stdio.h>
  char *gets( char *str );

The gets() function reads characters from STDIN and loads them into str, until a newline or EOF is reached. The newline character is translated into a null termination. The return value of gets() is the read-in string, or NULL if there is an error.

Related topics:
fputs(), fgetc(), fgets(), and puts().

perror

Syntax:
  #include <stdio.h>
  void perror( const char *str );

The perror() function prints str and an implementation-defined error message corresponding to the global variable errno.

printf

Syntax:
  #include <stdio.h>
  int printf( const char *format, ... );

The printf() function prints output to STDOUT, according to format and other arguments passed to printf(). The string format consists of two types of items - characters that will be printed to the screen, and format commands that define how the other arguments to printf() are displayed. Basically, you specify a format string that has text in it, as well as "special" characters that map to the other arguments of printf(). For example, this code

    char name[20] = "Bob";
    int age = 21;
    printf( "Hello %s, you are %d years old\n", name, age );

displays the following output:

    Hello Bob, you are 21 years old

The %s means, "insert the first argument, a string, right here." The %d indicates that the second argument (an integer) should be placed there. There are different %-codes for different variable types, as well as options to limit the length of the variables and whatnot.

Code | Format
%c | character
%d | signed integers
%i | signed integers
%e | scientific notation, with a lowercase "e"
%E | scientific notation, with a uppercase "E"
%f | floating point
%g | use %e or %f, whichever is shorter
%G | use %E or %f, whichever is shorter
%o | octal
%s | a string of characters
%u | unsigned integer
%x | unsigned hexadecimal, with lowercase letters
%X | unsigned hexadecimal, with uppercase letters
%p | a pointer
%n | the argument shall be a pointer to an integer into which is placed the number of characters written so far
%% | a '%' sign

An integer placed between a % sign and the format command acts as a minimum field width specifier, and pads the output with spaces or zeros to make it long enough. If you want to pad with zeros, place a zero before the minimum field width specifier. You can use a precision modifier, which has different meanings depending on the format code being used.

  • With %e, %E, and %f, the precision modifier lets you specify the number of decimal places desired. For example,

        %12.6f

    will display a floating number at least 12 digits wide, with six decimal places.

  • With %g and %G, the precision modifier determines the maximum number of significant digits displayed.
  • With %s, the precision modifer simply acts as a maximumfield length, to complement the minimum field length that precedes the period.
All of printf()'s output is right-justified, unless you place a minus sign right after the % sign. For example,

    %-12.4f

will display a floating point number with a minimum of 12 characters, 4 decimal places, and left justified. You may modify the %d, %i, %o, %u, and %x type specifiers with the letter l and the letter h to specify long and short data types (e.g. %hd means a short integer). The %e, %f, and %g type specifiers can have the letter l before them to indicate that a double follows. The %g, %f, and %e type specifiers can be preceded with the character '#' to ensure that the decimal point will be present, even if there are no decimal digits. The use of the '#' character with the %x type specifier indicates that the hexidecimal number should be printed with the '0x' prefix. The use of the '#' character with the %o type specifier indicates that the octal value should be displayed with a 0 prefix.

You can also include constant escape sequences in the output string.

The return value of printf() is the number of characters printed, or a negative number if an error occurred.

Related topics:
scanf() and fprintf().

putc

Syntax:
  #include <stdio.h>
  int putc( int ch, FILE *stream );

The putc() function writes the character ch to stream. The return value is the character written, or EOF if there is an error. For example:

    char ch;
    FILE *input, *output;
    input = fopen( "tmp.c", "r" );
    output = fopen( "tmpCopy.c", "w" );
    ch = getc( input );
    while( ch != EOF ) {
      putc( ch, output );
      ch = getc( input );
    }
    fclose( input );
    fclose( output );

generates a copy of the file tmp.c called tmpCopy.c.

Related topics:
fgetc(), fputc(), getchar(), and putchar().

putchar

Syntax:
  #include <stdio.h>
  int putchar( int ch );

The putchar() function writes ch to STDOUT. The code

    putchar( ch );

is the same as

    putc( ch, STDOUT );

The return value of putchar() is the written character, or EOF if there is an error.

Related topics:
putc()

puts

Syntax:
  #include <stdio.h>
  int puts( char *str );

The function puts() writes str to STDOUT. puts() returns non-negative on success, or EOF on failure.

Related topics:
putc(), gets(), and printf().

remove

Syntax:
  #include <stdio.h>
  int remove( const char *fname );

The remove() function erases the file specified by fname. The return value of remove() is zero upon success, and non-zero if there is an error.

Related topics:
rename()

rename

Syntax:
  #include <stdio.h>
  int rename( const char *oldfname, const char *newfname );

The function rename() changes the name of the file oldfname to newfname. The return value of rename() is zero upon success, non-zero on error.

Related topics:
remove()

rewind

Syntax:
  #include <stdio.h>
  void rewind( FILE *stream );

The function rewind() moves the file position indicator to the beginning of the specified stream, also clearing the error and EOF flags associated with that stream.

Related topics:
fseek()

scanf

Syntax:
  #include <stdio.h>
  int scanf( const char *format, ... );

The scanf() function reads input from stdin, according to the given format, and stores the data in the other arguments. It works a lot like printf(). The format string consists of control characters, whitespace characters, and non-whitespace characters. The control characters are preceded by a % sign, and are as follows:

Control Character | Explanation
%c | a single character
%d | a decimal integer
%i | an integer
%e, %f, %g | a floating-point number
%o | an octal number
%s | a string
%x | a hexadecimal number
%p | a pointer
%n | an integer equal to the number of characters read so far
%u | an unsigned integer
%[] | a set of characters
%% | a percent sign

scanf() reads the input, matching the characters from format. When a control character is read, it puts the value in the next variable. Whitespace (tabs, spaces, etc) are skipped. Non-whitespace characters are matched to the input, then discarded. If a number comes between the % sign and the control character, then only that many characters will be converted into the variable. If scanf() encounters a set of characters, denoted by the %[] control character, then any characters found within the brackets are read into the variable. The return value of scanf() is the number of variables that were successfully assigned values, or EOF if there is an error.

Related topics:
printf() and fscanf().

setbuf

Syntax:
  #include <stdio.h>
  void setbuf( FILE *stream, char *buffer );

The setbuf() function sets stream to use buffer, or, if buffer is null, turns off buffering. If a non-standard buffer size is used, it should by BUFSIZ characters long.

Related topics:
fopen(), fclose(), setvbuf(),

setvbuf

Syntax:
  #include <stdio.h>
  int setvbuf( FILE *stream, char *buffer, int mode, size_t size );

The function setvbuf() sets the buffer for stream to be buffer, with a size of size. mode can be:

  • _IOFBF, which indicates full buffering
  • _IOLBF, which means line buffering
  • _IONBF, which means no buffering

Related topics:
setbuf(),

sprintf

Syntax:
  #include <stdio.h>
  int sprintf( char *buffer, const char *format, ... );

The sprintf() function is just like printf(), except that the output is sent to buffer. The return value is the number of characters written. For example:

    char string[50];
    int file_number = 0;

    sprintf( string, "file.%d", file_number );
    file_number++;
    output_file = fopen( string, "w" );
Related topics:
printf(), fsprintf(),

sscanf

Syntax:
  #include <stdio.h>
  int sscanf( const char *buffer, const char *format, ... );

The function sscanf() is just like scanf(), except that the input is read from buffer.

Related topics:
scanf(), fscanf(),

tmpfile

Syntax:
  #include <stdio.h>
  FILE *tmpfile( void );

The function tempfile() opens a temporary file with an unique filename and returns a pointer to that file. If there is an error, null is returned.

Related topics:
tmpnam(),

tmpnam

Syntax:
  #include <stdio.h>
  char *tmpnam( char *name );

The tmpnam() function creates an unique filename and stores it in name. tmpnam() can be called up to TMP_MAX times.

Related topics:
tmpfile(),

ungetc

Syntax:
  #include <stdio.h>
  int ungetc( int ch, FILE *stream );

The function ungetc() puts the character ch back in stream.

Related topics:
getc(),

vprintf, vfprintf, and vsprintf

Syntax:
  #include <stdarg.h>
  #include <stdio.h>
  int vprintf( char *format, va_list arg_ptr );
  int vfprintf( FILE *stream, const char *format, va_list arg_ptr );
  int vsprintf( char *buffer, char *format, va_list arg_ptr );

These functions are very much like printf(), fprintf(), and sprintf(). The difference is that the argument list is a pointer to a list of arguments. va_list is defined in STDARG.H, and is also used by va_arg(). For example:

    void error( char *fmt, ... ) {
      va_list args;

      va_start( args, fmt );
      fprintf( stderr, "Error: " );
      vfprintf( stderr, fmt, args );
      fprintf( stderr, "\n" );
      va_end( args );
      exit( 1 );
    }


Standard C String & Character

cppreference.com -> Standard C String & Character

Standard C string and character

atof() | converts a string to a double
atoi() | converts a string to an integer
atol() | converts a string to a long
isalnum() | true if alphanumeric
isalpha() | true if alphabetic
iscntrl() | true if control character
isdigit() | true if digit
isgraph() | true if a graphical character
islower() | true if lowercase
isprint() | true if a printing character
ispunct() | true if punctuation
isspace() | true if space
isupper() | true if uppercase character
isxdigit() | true if a hexidecimal character
memchr() | searches an array for the first occurance of a character
memcmp() | compares two buffers
memcpy() | copies one buffer to another
memmove() | moves one buffer to another
memset() | fills a buffer with a character
strcat() | concatenates two strings
strchr() | finds the first occurance of a character in a string
strcmp() | compares two strings
strcoll() | compares two strings in accordance to the current locale
strcpy() | copies one string to another
strcspn() | searches one string for any characters in another
strerror() | returns a text version of a given error code
strlen() | returns the length of a given string
strncat() | concatenates a certain amount of characters of two strings
strncmp() | compares a certain amount of characters of two strings
strncpy() | copies a certain amount of characters from one string to another
strpbrk() | finds the first location of any character in one string, in another string
strrchr() | finds the last occurance of a character in a string
strspn() | returns the length of a substring of characters of a string
strstr() | finds the first occurance of a substring of characters
strtod() | converts a string to a double
strtok() | finds the next token in a string
strtol() | converts a string to a long
strtoul() | converts a string to an unsigned long
strxfrm() | converts a substring so that it can be used by string comparison functions
tolower() | converts a character to lowercase
toupper() | converts a character to uppercase


Standard C String & Character

atof

Syntax:
  #include <stdlib.h>
  double atof( const char *str );

The function atof() converts str into a double, then returns that value. str must start with a valid number, but can be terminated with any non-numerical character, other than "E" or "e". For example,

    x = atof( "42.0is_the_answer" );

results in x being set to 42.0.

Related topics:
atoi() and atol().

atoi

Syntax:
  #include <stdlib.h>
  int atoi( const char *str );

The atoi() function converts str into an integer, and returns that integer. str should start with some sort of number, and atoi() will stop reading from str as soon as a non-numerical character has been read. For example,

    i = atoi( "512.035" );

would result in i being set to 512.

Related topics:
atof() and atol().

atol

Syntax:
  #include <stdlib.h>
  long atol( const char *str );

The function atol() converts str into a long, then returns that value. atol() will read from str until it finds any character that should not be in a long. The resulting truncated value is then converted and returned. For example,

    x = atol( "1024.0001" );

results in x being set to 1024L.

Related topics:
atof() and atoi().

isalnum

Syntax:
  #include <ctype.h>
  int isalnum( int ch );

The function isalnum() returns non-zero if its argument is a numeric digit or a letter of the alphabet. Otherwise, zero is returned.

    char c;
    scanf( "%c", &c );
    if( isalnum(c) )
      printf( "You entered the alphanumeric character %c\n", c );
Related topics:
isalpha(), iscntrl(), isdigit(), isgraph(), isprint(), ispunct(), and isspace().

isalpha

Syntax:
  #include <ctype.h>
  int isalpha( int ch );

The function isalpha() returns non-zero if its argument is a letter of the alphabet. Otherwise, zero is returned.

    char c;
    scanf( "%c", &c );
    if( isalpha(c) )
      printf( "You entered a letter of the alphabet\n" );
Related topics:
isalnum(), iscntrl(), isdigit(), isgraph(), isprint(), ispunct(), and isspace().

iscntrl

Syntax:
  #include <ctype.h>
  int iscntrl( int ch );

The iscntrl() function returns non-zero if its argument is a control character (between 0 and 0x1F or equal to 0x7F). Otherwise, zero is returned.

Related topics:
isalnum(), isalpha(), isdigit(), isgraph(), isprint(), ispunct(), and isspace().

isdigit

Syntax:
  #include <ctype.h>
  int isdigit( int ch );

The function isdigit() returns non-zero if its argument is a digit between 0 and 9. Otherwise, zero is returned.

    char c;
    scanf( "%c", &c );
    if( isdigit(c) )
      printf( "You entered the digit %c\n", c );
Related topics:
isalnum(), isalpha(), iscntrl(), isgraph(), isprint(), ispunct(), and isspace().

isgraph

Syntax:
  #include <ctype.h>
  int isgraph( int ch );

The function isgraph() returns non-zero if its argument is any printable character other than a space (if you can see the character, then isgraph() will return a non-zero value). Otherwise, zero is returned.

Related topics:
isalnum(), isalpha(), iscntrl(), isdigit(), isprint(), ispunct(), and isspace().

islower

Syntax:
  #include <ctype.h>
  int islower( int ch );

The islower() function returns non-zero if its argument is a lowercase letter. Otherwise, zero is returned.

Related topics:
isupper()

isprint

Syntax:
  #include <ctype.h>
  int isprint( int ch );

The function isprint() returns non-zero if its argument is a printable character (including a space). Otherwise, zero is returned.

Related topics:
isalnum(), isalpha(), iscntrl(), isdigit(), isgraph(), ispunct(), and isspace().

ispunct

Syntax:
  #include <ctype.h>
  int ispunct( int ch );

The ispunct() function returns non-zero if its argument is a printing character but neither alphanumeric nor a space. Otherwise, zero is returned.

Related topics:
isalnum(), isalpha(), iscntrl(), isdigit(), isgraph(), isprint(), and isspace().

isspace

Syntax:
  #include <ctype.h>
  int isspace( int ch );

The isspace() function returns non-zero if its argument is some sort of space (i.e. single space, tab, vertical tab, form feed, carriage return, or newline). Otherwise, zero is returned.

Related topics:
isalnum(), isalpha(), iscntrl(), isdigit(), isgraph(), and ispunct().

isupper

Syntax:
  #include <ctype.h>
  int isupper( int ch );

The isupper() function returns non-zero if its argument is an uppercase letter. Otherwise, zero is returned.

Related topics:
tolower()

isxdigit

Syntax:
  #include <ctype.h>
  int isxdigit( int ch );

The function isxdigit() returns non-zero if its argument is a hexidecimal digit (i.e. A-F, a-f, or 0-9). Otherwise, zero is returned.

Related topics:
isalnum(), isalpha(), iscntrl(), isdigit(), isgraph(), ispunct(), and isspace().

memchr

Syntax:
  #include <string.h>
  void *memchr( const void *buffer, int ch, size_t count );

The memchr() function looks for the first occurrence of ch within count characters in the array pointed to by buffer. The return value points to the location of the first occurrence of ch, or NULL if ch isn't found. For example:

    char names[] = "Alan Bob Chris X Dave";
    if( memchr(names,'X',strlen(names)) == NULL )
      printf( "Didn't find an X\n" );
    else
      printf( "Found an X\n" );
Related topics:
memcpy() and strstr().

memcmp

Syntax:
  #include <string.h>
  int memcmp( const void *buffer1, const void *buffer2, size_t count );

The function memcmp() compares the first count characters of buffer1 and buffer2. The return values are as follows:

Value | Explanation
less than 0 | buffer1 is less than buffer2
equal to 0 | buffer1 is equal to buffer2
greater than 0 | buffer1 is greater than buffer2

Related topics:
memchr(), memcpy(), and strcmp().

memcpy

Syntax:
  #include <string.h>
  void *memcpy( void *to, const void *from, size_t count );

The function memcpy() copies count characters from the array from to the array to. memcpy() returns to. The behavior of memcpy() is undefined if to and from overlap.

Related topics:
memmove().

memmove

Syntax:
  #include <string.h>
  void *memmove( void *to, const void *from, size_t count );

The memmove() function is identical to memcpy(), except that it works even if to and from overlap.

Related topics:
memcpy().

memset

Syntax:
  #include <string.h>
  void *memset( void *buffer, int ch, size_t count );

The function memset() copies ch into the first count characters of buffer, and returns buffer. memset() is useful for intializing a section of memory to some value. For example, this command:

    memset( the_array, '\0', sizeof(the_array) );

is a very efficient way to set all values of the_array to zero.

Related topics:
memcmp(), memcpy(), and memmove().

strcat

Syntax:
  #include <string.h>
  char *strcat( char *str1, const char *str2 );

The strcat() function concatenates str2 onto the end of str1, and returns str1. For example:

    printf( "Enter your name: " );
    scanf( "%s", name );
    title = strcat( name, " the Great" );
    printf( "Hello, %s\n", title );
Related topics:
strchr(), strcmp(), and strcpy().

strchr

Syntax:
  #include <string.h>
  char *strchr( const char *str, int ch );

The function strchr() returns a pointer to the first occurence of ch in str, or NULL if ch is not found.

Related topics:
strpbrk(), strspn(), strstr(), and strtok().

strcmp

Syntax:
  #include <string.h>
  int strcmp( const char *str1, const char *str2 );

The function strcmp() compares str1 and str2, then returns:

Return value | Explanation
less than 0 | str1 is less than str2
equal to 0 | str1 is equal to str2
greater than 0 | str1 is greater than str2

For example:

    printf( "Enter your name: " );
    scanf( "%s", name );
    if( strcmp( name, "Mary" ) == 0 )
      printf( "Hello, Dr. Mary!\n" );
Related topics:
memcmp(), strchr(), strcpy(), and strncmp().

strcoll

Syntax:
  #include <string.h>
  int strcoll( const char *str1, const char *str2 );

The strcoll() function compares str1 and str2, much like strcmp. However, strcoll() performs the comparison using the locale specified by the setlocale() function.

strcpy

Syntax:
  #include <string.h>
  char *strcpy( char *to, const char *from );

The strcpy() function copies characters in the string from to the string to, including the null termination. The return value is to.

Related topics:
memcpy(), strchr(), strcmp(), strncmp(), and strncpy().

strcspn

Syntax:
  #include <string.h>
  size_t strcspn( const char *str1, const char *str2 );

The function strcspn() returns the index of the first character in str1 that matches any of the characters in str2.

Related topics:
strrchr(), strpbrk(), strstr(), and strtok().

strerror

Syntax:
  #include <string.h>
  char *strerror( int num );

The function strerror() returns an "implementation defined string corresponding to num."

strlen

Syntax:
  #include <string.h>
  size_t strlen( char *str );

The strlen() function returns the length of str (determined by the number of characters before null termination).

Related topics:
memcpy(), strchr(), strcmp(), and strncmp().

strncat

Syntax:
  #include <string.h>
  char *strncat( char *str1, const char *str2, size_t count );

The function strncat() concatenates at most count characters of str2 onto str1, adding a null termination. The resulting string is returned.

Related topics:
strcat(), strnchr(), strncmp(), and strncpy().

strncmp

Syntax:
  #include <string.h>
  int strncmp( const char *str1, const char *str2, size_t count );

The strncmp() function compares at most count characters of str1 and str2. The return value is as follows:

Return value | Explanation
less than 0 | str1 is less than str2
equal to 0 | str1 is equal to str2
greater than 0 | str1 is greater than str2

If there are less than count characters in either string, then the comparison will stop after the first null termination is encountered.

Related topics:
strcmp(), strnchr(), and strncpy().

strncpy

Syntax:
  #include <string.h>
  char *strncpy( char *to, const char *from, size_t count );

The strncpy() function copies at most count characters of from to the string to. If from has less than count characters, the remainder is padded with '\0' characters. The return value is the resulting string.

Related topics:
memcpy(), strchr(), strncat(), and strncmp().

strpbrk

Syntax:
  #include <string.h>
  char *strpbrk( const char *str1, const char *str2 );

The function strpbrk() returns a pointer to the first ocurrence in str1 of any character in str2, or NULL if none are present.

Related topics:
strspn(), strrchr(), strstr(), and strtok().

strrchr

Syntax:
  #include <string.h>
  char *strrchr( const char *str, int ch );

The function strrchr() returns a pointer to the last occurrence of ch in str, or NULL if no match is found.

Related topics:
strpbrk(), strspn(), strstr(), strtok(),

strspn

Syntax:
  #include <string.h>
  size_t strspn( const char *str1, const char *str2 );

The strspn() function returns the index of the first character in str1 that doesn't match any character in str2.

Related topics:
strpbrk(), strrchr(), strstr(), strtok(),

strstr

Syntax:
  #include <string.h>
  char *strstr( const char *str1, const char *str2 );

The function strstr() returns a pointer to the first occurrence of str2 in str1, or NULL if no match is found.

Related topics:
strchr(), strcspn(), strpbrk(), strspn(), strtok(), strrchr(),

strtod

Syntax:
  #include <stdlib.h>
  double strtod( const char *start, char **end );

The function strtod() returns whatever it encounters first in start as a double. end is set to point at whatever is left in start after that double. If overflow occurs, strtod() returns either HUGE_VAL or -HUGE_VAL.

Related topics:
atof()

strtok

Syntax:
  #include <string.h>
  char *strtok( char *str1, const char *str2 );

The strtok() function returns a pointer to the next "token" in str1, where str2 contains the delimiters that determine the token. strtok() returns NULL if no token is found. In order to convert a string to tokens, the first call to strtok() should have str1 point to the string to be tokenized. All calls after this should have str1 be NULL.

For example:

    char str[] = "now # is the time for all # good men to come to the # aid of their country";
    char delims[] = "#";
    char *result = NULL;
    result = strtok( str, delims );
    while( result != NULL ) {
        printf( "result is \"%s\"\n", result );
        result = strtok( NULL, delims );
    }

The above code will display the following output:

    result is "now "
    result is " is the time for all "
    result is " good men to come to the "
    result is " aid of their country"
Related topics:
strchr(), strcspn(), strpbrk(), strrchr(), and strspn().

strtol

Syntax:
  #include <stdlib.h>
  long strtol( const char *start, char **end, int base );

The strtol() function returns whatever it encounters first in start as a long, doing the conversion to base if necessary. end is set to point to whatever is left in start after the long. If the result can not be represented by a long, then strtol() returns either LONG_MAX or LONG_MIN. Zero is returned upon error.

Related topics:
atol().

strtoul

Syntax:
  #include <stdlib.h>
  unsigned long strtoul( const char *start, char **end, int base );

The function strtoul() behaves exactly like strtol(), except that it returns an unsigned long rather than a mere long.

Related topics:
strtol()

strxfrm

Syntax:
  #include <string.h>
  size_t strxfrm( char *str1, const char *str2, size_t num );

The strxfrm() function manipulates the first num characters of str2 and stores them in str1. The result is such that if a strcoll() is performed on str1 and the old str2, you will get the same result as with a strcmp().

Related topics:
strcmp(), strcoll(),

tolower

Syntax:
  #include <ctype.h>
  int tolower( int ch );

The function tolower() returns the lowercase version of the character ch.

Related topics:
toupper(),

toupper

Syntax:
  #include <ctype.h>
  int toupper( int ch );

The toupper() function returns the uppercase version of the character ch.

Related topics:
tolower(),


Standard C Math

abs() | absolute value
acos() | arc cosine
asin() | arc sine
atan() | arc tangent
atan2() | arc tangent, using signs to determine quadrants
ceil() | the smallest integer not less than a certain value
cos() | cosine
cosh() | hyperbolic cosine
div() | returns the quotient and remainder of a division
exp() | returns "e" raised to a given power
fabs() | absolute value for floating-point numbers
floor() | returns the largest integer not greater than a given value
fmod() | returns the remainder of a division
frexp() | decomposes a number into scientific notation
labs() | absolute value for long integers
ldexp() | computes a number in scientific notation
ldiv() | returns the quotient and remainder of a division, in long integer form
log() | natural logarithm
log10() | natural logarithm, in base 10
modf() | decomposes a number into integer and fractional parts
pow() | returns a given number raised to another number
sin() | sine
sinh() | hyperbolic sine
sqrt() | square root
tan() | tangent
tanh() | hyperbolic tangent


Standard C Math

abs

Syntax:
  #include <stdlib.h>
  int abs( int num );

The abs() function returns the absolute value of num. For example:

    int magic_number = 10;
    cout << "Enter a guess: ";
    cin >> x;
    cout << "Your guess was " << abs( magic_number - x ) << " away from the magic number." << endl;
Related topics:
labs().

acos

Syntax:
  #include <math.h>
  double acos( double arg );

The acos() function returns the arc cosine of arg. arg should be between -1 and 1.

Related topics:
asin(), atan(), atan2(), sin(), cos(), tan(), sinh(), cosh(), and tanh().

asin

Syntax:
  #include <math.h>
  double asin( double arg );

The asin() function returns the arc sine of arg. arg should be between -1 and 1.

Related topics:
acos(), atan(), atan2(), sin(), cos(), tan(), sinh(), cosh(), and tanh().

atan

Syntax:
  #include <math.h>
  double atan( double arg );

The function atan() returns the arc tangent of arg.

Related topics:
asin(), acos(), atan2(), sin(), cos(), tan(), sinh(), cosh(), and tanh().

atan2

Syntax:
  #include <math.h>
  double atan2( double y, double x );

The atan2() function computes the arc tangent of y/x, using the signs of the arguments to compute the quadrant of the return value.

Related topics:
asin(), acos(), atan(), sin(), cos(), tan(), sinh(), cosh(), and tanh().

ceil

Syntax:
  #include <math.h>
  double ceil( double num );

The ceil() function returns the smallest integer no less than num. For example,

    y = 6.04;
    x = ceil( y );

would set x to 7.0.

Related topics:
floor() and fmod().

cos

Syntax:
  #include <math.h>
  double cos( double arg );

The cos() function returns the cosine of arg, where arg is expressed in radians.

Related topics:
asin(), acos(), atan(), sin(), atan2(), tan(), sinh(), cosh(), and tanh().

cosh

Syntax:
  #include <math.h>
  double cosh( double arg );

The function cosh() returns the hyperbolic cosine of arg.

Related topics:
asin(), acos(), atan(), sin(), atan2(), tan(), sinh(), cos(), and tanh().

div

Syntax:
  #include <stdlib.h>
  div_t div( int numerator, int denominator );

The function div() returns the quotient and remainder of the operation numerator / denominator. The div_t structure is defined in stdlib.h, and has at least:

    int quot;   // The quotient
    int rem;    // The remainder

For example, the following code displays the quotient and remainder of x/y:

    div_t temp;
    temp = div( x, y );
    printf( "%d divided by %d yields %d with a remainder of %d\n", x, y, temp.quot, temp.rem );
Related topics:
ldiv().

exp

Syntax:
  #include <math.h>
  double exp( double arg );

The exp() function returns e (2.7182818) raised to the argth power.

Related topics:
log().

fabs

Syntax:
  #include <math.h>
  double fabs( double arg );

The function fabs() returns the absolute value of arg.

Related topics:
abs().

floor

Syntax:
  #include <math.h>
  double floor( double arg );

The function floor() returns the largest integer not greater than arg. For example,

    y = 6.04;
    x = floor( y );

would result in x being set to 6.0.

Related topics:
ceil().

fmod

Syntax:
  #include <math.h>
  double fmod( double x, double y );

The fmod() function returns the remainder of x/y.

Related topics:
ceil(), floor(), and fabs().

frexp

Syntax:
  #include <math.h>
  double frexp( double num, int *exp );

The function frexp() is used to decompose num into two parts: a mantissa between 0.5 and 1 (returned by the function) and an exponent returned as exp. Scientific notation works like this:

    num = mantissa * (2 ^ exp)
Related topics:
ldexp().

labs

Syntax:
  #include <stdlib.h>
  long labs( long num );

The function labs() returns the absolute value of num.

Related topics:
abs().

ldexp

Syntax:
  #include <math.h>
  double ldexp( double num, int exp );

The ldexp() function returns num * (2 ^ exp). And get this: if an overflow occurs, HUGE_VAL is returned.

Related topics:
frexp() and modf().

ldiv

Syntax:
  #include <stdlib.h>
  ldiv_t ldiv( long numerator, long denominator );

The ldiv() function returns the quotient and remainder of the operation numerator / denominator. The ldiv_t structure is defined in stdlib.h and has at least:

    long quot;  // the quotient
    long rem;   // the remainder
Related topics:
div().

log

Syntax:
  #include <math.h>
  double log( double num );

The function log() returns the natural logarithm of num. There's a domain error if num is negative, a range error if num is zero.

Related topics:
log10().

log10

Syntax:
  #include <math.h>
  double log10( double num );

The log10() function returns the base 10 logarithm for num. There's a domain error if num is negative, a range error if num is zero.

Related topics:
log().

modf

Syntax:
  #include <math.h>
  double modf( double num, double *i );

The function modf() splits num into its integer and fraction parts. It returns the fractional part and loads the integer part into i.

Related topics:
frexp() and ldexp().

pow

Syntax:
  #include <math.h>
  double pow( double base, double exp );

The pow() function returns base raised to the exp power. There's a domain error if base is zero and exp is less than or equal to zero. There's also a domain error if base is negative and exp is not an integer. There's a range error if there's an overflow.

Related topics:
exp(), log(), and sqrt().

sin

Syntax:
  #include <math.h>
  double sin( double arg );

The function sin() returns the sine of arg, where arg is given in radians.

Related topics:
asin(), acos(), atan(), cosh(), atan2(), tan(), sinh(), cos(), and tanh().

sinh

Syntax:
  #include <math.h>
  double sinh( double arg );

The function sinh() returns the hyperbolic sine of arg.

Related topics:
asin(), acos(), atan(), cosh(), atan2(), tan(), sin(), cos(), and tanh().

sqrt

Syntax:
  #include <math.h>
  double sqrt( double num );

The sqrt() function returns the square root of num. If num is negative, a domain error occurs.

Related topics:
exp(), log(), and pow().

tan

Syntax:
  #include <math.h>
  double tan( double arg );

The tan() function returns the tangent of arg, where arg is given in radians.

Related topics:
asin(), acos(), atan(), cosh(), atan2(), sinh(), sin(), cos(), and tanh().

tanh

Syntax:
  #include <math.h>
  double tanh( double arg );

The function tanh() returns the hyperbolic tangent of arg.

Related topics:
asin(), acos(), atan(), cosh(), atan2(), tan(), sin(), cos(), and sinh().


Standard C Time & Date

asctime() | a textual version of the time
clock() | returns the amount of time that the program has been running
ctime() | returns a specifically formatted version of the time
difftime() | the difference between two times
gmtime() | returns a pointer to the current Greenwich Mean Time
localtime() | returns a pointer to the current time
mktime() | returns the calendar version of a given time
strftime() | returns individual elements of the date and time
time() | returns the current calendar time of the system


Standard C Date & Time

asctime

Syntax:
  #include <time.h>
  char *asctime( const struct tm *ptr );

The function asctime() converts the time in the struct ptr to a character string of the following format:

    day month date hours:minutes:seconds year\n\0

An example:

    Mon Jun 26 12:03:53 2000
Related topics:
localtime(), gmtime(), time(), and ctime().

clock

Syntax:
  #include <time.h>
  clock_t clock( void );

The clock() function returns the processor time since the program started, or -1 if that information is unavailable. To convert the return value to seconds, divide it by CLOCKS_PER_SEC. (Note: if your compiler is POSIX compliant, then CLOCKS_PER_SEC is always defined as 1000000.)

Related topics:
time(), asctime(), and ctime().

ctime

Syntax:
  #include <time.h>
  char *ctime( const time_t *time );

The ctime() function converts the calendar time time to local time of the format:

    day month date hours:minutes:seconds year\n\0

using ctime() is equivalent to

    asctime( localtime( tp ) );
Related topics:
localtime(), gmtime(), time(), and asctime().

difftime

Syntax:
  #include <time.h>
  double difftime( time_t time2, time_t time1 );

The function difftime() returns time2-time1, in seconds.

Related topics:
localtime(), gmtime(), time(), and asctime().

gmtime

Syntax:
  #include <time.h>
  struct tm *gmtime( const time_t *time );

The gmtime() function returns the given time in Coordinated Universal Time (usually Greenwich mean time), unless it's not supported by the system, in which case NULL is returned. Warning!

Related topics:
localtime(), time(), and asctime().

localtime

Syntax:
  #include <time.h>
  struct tm *localtime( const time_t *time );

The function localtime() converts calendar time time into local time. Warning!

Related topics:
gmtime(), time(), and asctime().

mktime

Syntax:
  #include <time.h>
  time_t mktime( struct tm *time );

The mktime() function converts the local time in time to calendar time, and returns it. If there is an error, -1 is returned.

Related topics:
time(), gmtime(), asctime(), and ctime().

strftime

Syntax:
  #include <time.h>
  size_t strftime( char *str, size_t maxsize, const char *fmt, struct tm *time );

The function strftime() formats date and time information from time to a format specified by fmt, then stores the result in str (up to maxsize characters). Certain codes may be used in fmt to specify different types of time:

Code | Meaning
%a | abbreviated weekday name
%A | full weekday name
%b | abbreviated month name
%B | full month name
%c | the standard date and time string
%d | day of the month, as a number (1-31)
%H | hour, 24 hour format (0-23)
%I | hour, 12 hour format (1-12)
%j | day of the year, as a number (1-366)
%m | month as a number (1-12). Note: some versions of Microsoft Visual C++ may use values that range from 0-11.
%M | minute as a number (0-59)
%p | locale's equivalent of AM or PM
%S | second as a number (0-59)
%U | week of the year, sunday as the first day
%w | weekday as a decimal (0-6, sunday=0)
%W | week of the year, monday as the first day
%x | standard date string
%X | standard time string
%y | year in decimal, without the century (0-99)
%Y | year in decimal, with the century
%Z | time zone name
%% | a percent sign

The strftime() function returns the number of characters put into str, or zero if an error occurs.

Related topics:
time(), localtime(), and gmtime().

time

Syntax:
  #include <time.h>
  time_t time( time_t *time );

The function time() returns the current time, or -1 if there is an error. If the argument time is given, then the current time is stored in time.

Related topics:
localtime(), gmtime(), strftime(), ctime(),


Standard C Memory

calloc() | allocates a two-dimensional chunk of memory
free() | makes memory available for future allocation
malloc() | allocates memory
realloc() | changes the size of previously allocated memory


Standard C Memory

calloc

Syntax:
  #include <stdlib.h>
  void *calloc( size_t num, size_t size );

The calloc() function returns a pointer to space for an array of num objects, each of size size. calloc() returns NULL if there is an error.

Related topics:
free(), malloc(), and realloc().

free

Syntax:
  #include <stdlib.h>
  void free( void *ptr );

The free() function deallocates the space pointed to by ptr, freeing it up for future use. ptr must have been used in a previous call to malloc(), calloc(), or realloc(). An example:

    typedef struct data_type {
      int age;
      char name[20];
    } data;

    data *willy;
    willy = (data*) malloc( sizeof(willy) );
    ...
    free( willy );
Related topics:
calloc(), malloc(), and realloc().

malloc

Syntax:
  #include <stdlib.h>
  void *malloc( size_t size );

The function malloc() returns a pointer to a chunk of memory of size size, or NULL if there is an error. The memory pointed to will be on the heap, not the stack, so make sure to free it when you are done with it. An example:

    typedef struct data_type {
      int age;
      char name[20];
    } data;

    data *bob;
    bob = (data*) malloc( sizeof(data) );
    if( bob != NULL ) {
      bob->age = 22;
      strcpy( bob->name, "Robert" );
      printf( "%s is %d years old\n", bob->name, bob->age );
    }
    free( bob );
Related topics:
free(), realloc(), and calloc().

realloc

Syntax:
  #include <stdlib.h>
  void *realloc( void *ptr, size_t size );

The realloc() function changes the size of the object pointed to by ptr to the given size. size can be any size, larger or smaller than the original. The return value is a pointer to the new space, or NULL if there is an error.

Related topics:
free(), malloc(), and calloc().


Other standard C functions

abort() | stops the program
assert() | stops the program if an expression isn't true
atexit() | sets a function to be called when the program exits
bsearch() | perform a binary search
exit() | stop the program
getenv() | get enviornment information about a variable
longjmp() | start execution at a certain point in the program
qsort() | perform a quicksort
raise() | send a signal to the program
rand() | returns a pseudorandom number
setjmp() | set execution to start at a certain point
signal() | register a function as a signal handler
srand() | initialize the random number generator
system() | perform a system call
va_arg() | use variable length parameter lists


Other standard C functions

abort

Syntax:
  #include <stdlib.h>
  void abort( void );

The function abort() terminates the current program. Depending on the implementation, the return value can indicate failure.

Related topics:
exit() and atexit().

assert

Syntax:
  #include <assert.h>
  void assert( int exp );

The assert() macro is used to test for errors. If exp evaluates to zero, assert() writes information to STDERR and exits the program. If the macro NDEBUG is defined, the assert() macros will be ignored.

Related topics:
abort()

atexit

Syntax:
  #include <stdlib.h>
  int atexit( void (*func)(void) );

The function atexit() causes the function pointed to by func to be called when the program terminates. You can make multiple calls to atexit() (at least 32, depending on your compiler) and those functions will be called in reverse order of their establishment. The return value of atexit() is zero upon success, and nonzero on failure.

Related topics:
exit() and abort().

bsearch

Syntax:
  #include <stdlib.h>
  void *bsearch( const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );

The bsearch() function searches buf[0] to buf[num-1] for an item that matches key, using a binary search. The function compare should return negative if its first argument is less than its second, zero if equal, and positive if greater. The items in the array buf should be in ascending order. The return value of bsearch() is a pointer to the matching item, or NULL if none is found.

Related topics:
qsort().

exit

Syntax:
  #include <stdlib.h>
  void exit( int exit_code );

The exit() function stops the program. exit_code is passed on to be the return value of the program, where usually zero indicates success and non-zero indicates an error.

Related topics:
atexit() and abort().

getenv

Syntax:
  #include <stdlib.h>
  char *getenv( const char *name );

The function getenv() returns environmental information associated with name, and is very implementation dependent. NULL is returned if no information about name is available.

Related topics:
system().

longjmp

Syntax:
  #include <setjmp.h>
  void longjmp( jmp_buf envbuf, int status );

The function longjmp() causes the program to start executing code at the point of the last call to setjmp(). envbuf is usually set through a call to setjmp(). status becomes the return value of setjmp() and can be used to figure out where longjmp() came from. status should not be set to zero.

Related topics:
setjmp().

qsort

Syntax:
  #include <stdlib.h>
  void qsort( void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );

The qsort() function sorts buf (which contains num items, each of size size) using Quicksort. The compare function is used to compare the items in buf. compare should return negative if the first argument is less than the second, zero if they are equal, and positive if the first argument is greater than the second. qsort() sorts buf in ascending order.

Related topics:
bsearch().

raise

Syntax:
  #include <signal.h>
  int raise( int signal );

The raise() function sends the specified signal to the program. Some signals:

Signal | Meaning
SIGABRT | Termination error
SIGFPE | Floating pointer error
SIGILL | Bad instruction
SIGINT | User presed CTRL-C
SIGSEGV | Illegal memory access
SIGTERM | Terminate program

The return value is zero upon success, nonzero on failure.

Related topics:
signal()

rand

Syntax:
  #include <stdlib.h>
  int rand( void );

The function rand() returns a pseudorandom integer between zero and RAND_MAX. An example:

    srand( time(NULL) );
    for( i = 0; i < 10; i++ )
      printf( "Random number #%d: %d\n", i, rand() );
Related topics:
srand()

setjmp

Syntax:
  #include <setjmp.h>
  int setjmp( jmp_buf envbuf );

The setjmp() function saves the system stack in envbuf for use by a later call to longjmp(). When you first call setjmp(), its return value is zero. Later, when you call longjmp(), the second argument of longjmp() is what the return value of setjmp() will be. Confused? Read about longjmp().

Related topics:
longjmp()

signal

Syntax:
  #include <signal.h>
  void ( *signal( int signal, void (* func) (int)) ) (int);

The signal() function sets func to be called when signal is recieved by your program. func can be a custom signal handler, or one of these macros (defined in signal.h):

Macro | Explanation
SIG_DFL | default signal handling
SIG_IGN | ignore the signal

The return value of signal() is the address of the previously defined function for this signal, or SIG_ERR is there is an error.

srand

Syntax:
  #include <stdlib.h>
  void srand( unsigned seed );

The function srand() is used to seed the random sequence generated by rand(). For any given seed, rand() will generate a specific "random" sequence over and over again.

    srand( time(NULL) );
    for( i = 0; i < 10; i++ )
      printf( "Random number #%d: %d\n", i, rand() );
Related topics:
rand(), time().

system

Syntax:
  #include <stdlib.h>
  int system( const char *command );

The system() function runs the given command as a system call. The return value is usually zero if the command executed without errors. If command is NULL, system() will test to see if there is a command interpreter available. Non-zero will be returned if there is a command interpreter available, zero if not.

Related topics:
exit(),

va_arg

Syntax:
  #include <stdarg.h>
  type va_arg( va_list argptr, type );
  void va_end( va_list argptr );
  void va_start( va_list argptr, last_parm );

The va_arg() macros are used to pass a variable number of arguments to a function.

  1. First, you must have a call to va_start() passing a valid va_list and the mandatory first argument of the function. This first argument describes the number of parameters being passed.
  2. Next, you call va_arg() passing the va_list and the type of the argument to be returned. The return value of va_arg() is the current parameter.
  3. Repeat calls to va_arg() for however many arguments you have.
  4. Finally, a call to va_end() passing the va_list is necessary for proper cleanup.
For example:

    int sum( int, ... );
    int main( void ) {

      int answer = sum( 4, 4, 3, 2, 1 );
      printf( "The answer is %d\n", answer );

      return( 0 );
    }

    int sum( int num, ... ) {
      int answer = 0;
      va_list argptr;

      va_start( argptr, num );
      for( ; num > 0; num-- )
        answer += va_arg( argptr, int );

      va_end( argptr );
      return( answer );
    }

This code displays 10, which is 4+3+2+1.


C++ I/O

The <iostream> library automatically defines a few standard objects:

  • cout, an object of the ostream class, which displays data to the standard output device.
  • cerr, another object of the ostream class that writes unbuffered output to the standard error device.
  • clog, like cerr, but uses buffered output.
  • cin, an object of the istream class that reads data from the standard input device.

The <fstream> library allows programmers to do file input and output with the ifstream and ofstream classes.

Some of the behavior of the C++ I/O streams (precision, justification, etc) may be modified by manipulating various flags.

Constructors | Constructors
bad() | true if an error occurred
clear() | clear status flags
close() | close a stream
eof() | true if at the end-of-file
fail() | true if an error occurred
fill() | manipulate the default fill character
flags() | manipulate flags
flush() | empty the buffer
gcount() | number of characters read during last input
get() | read characters
getline() | read a line of characters
good() | true if no errors have occurred
ignore() | read and discard characters
open() | create an input stream
peek() | check the next input character
precision() | manipulate precision
put() | write characters
putback() | return characters to a stream
rdstate() | returns the status of the stream
read() | read characters
seekg() | perform random access on a stream
seekp() | perform random access on a stream
setf() | set format flags
sync_with_stdio() | synchronize with standard I/O
tellg() | read stream pointers
tellp() | read stream pointers
unsetf() | clear format flags
width() | manipulate the field width
write() | write characters


C++ I/O

Constructors

Syntax:
  fstream( const char *filename, openmode mode );
  ifstream( const char *filename, openmode mode );
  ofstream( const char *filename, openmode mode );

The fstream, ifstream, and ofstream objects are used to do file I/O. The optional mode defines how the file is to be opened, according to the ios stream mode flags. The optional filename specifies the file to be opened and associated with the stream. For example, the following code reads input data and appends the result to an output file.

    ifstream fin( "/tmp/data.txt" );
    ofstream fout( "/tmp/results.txt", ios::app );
    while( fin >> temp )
      fout << temp + 2 << endl;
    fin.close();
    fout.close();

Input and output file streams can be used in a similar manner to C++ predefined I/O streams, cin and cout.

Related topics:
close(), open()

bad

Syntax:
  bool bad();

The bad() function returns true if a fatal error with the current stream has occurred, false otherwise.

Related topics:
good()

clear

Syntax:
  void clear( iostate flags = goodbit );

The function clear() clears the flags associated with the current stream. The default flag is goodbit, which clears all flags. Otherwise, only flags are cleared.

Related topics:
rdstate()

close

Syntax:
  void close();

The close() function closes the associated file stream.

Related topics:
open()

eof

Syntax:
  bool eof();

The function eof() returns true if the end of the associated input file has been reached, false otherwise. For example:

    char ch;
    ifstream fin( "temp.txt" );
    while( !fin.eof() ) {
      fin >> ch;
      cout << ch;
    }
    fin.close();
Related topics:
bad(), fail(), good(), rdstate(), clear()

fail

Syntax:
  bool fail();

The fail() function returns true if an error has occurred with the current stream, false otherwise.

Related topics:
good(), eof(), bad(), clear(), rdstate()

fill

Syntax:
  char fill();
  char fill( char ch );

The function fill() either returns the current fill character, or sets the current fill character to ch. The fill character is defined as the character that is used for padding when a number is smaller than the specified width. The default fill character is the space character.

Related topics:
precision(), width()

flags

Syntax:
  fmtflags flags();
  fmtflags flags( fmtflags f );

The flags() function either returns the format flags for the current stream, or sets the flags for the current stream to be f.

Related topics:
unsetf(), setf()

flush

Syntax:
  ostream &flush();

The flush() function causes the buffer for the current output stream to be actually written out to the attached device. This function is useful for printing out debugging information, because sometimes programs abort before they have a chance to write their output buffers to the screen. Judicious use of flush() can ensure that all of your debugging statements actually get printed.

Related topics:
put(), write()

gcount

Syntax:
  streamsize gcount();

The function gcount() is used with input streams, and returns the number of characters read by the last input operation.

Related topics:
get(), getline(), read()

get

Syntax:
  int get();
  istream &get( char &ch );
  istream &get( char *buffer, streamsize num );
  istream &get( char *buffer, streamsize num, char delim );
  istream &get( streambuf &buffer );
  istream &get( streambuf &buffer, char delim );

The get() function is used with input streams, and either:

  • reads a character and returns that value,
  • reads a character and stores it as ch,
  • reads characters into buffer until num - 1 characters have been read, or EOF or newline encountered,
  • reads characters into buffer until num - 1 characters have been read, or EOF or the delim character encountered (delim is not read until next time),
  • reads characters into buffer until a newline or EOF is encountered,
  • or reads characters into buffer until a newline, EOF, or delim character is encountered (again, delim isn't read until the next get() ).
For example, the following code displays the contents of temp.txt, character by character:

    char ch;
    ifstream fin( "temp.txt" );
    while( fin.get(ch) )
      cout << ch;
    fin.close();
Related topics:
put(), read(), getline()

getline

Syntax:
  istream &getline( char *buffer, streamsize num );
  istream &getline( char *buffer, streamsize num, char delim );

The getline() function is used with input streams, and reads characters into buffer until either:

  • num - 1 characters have been read,
  • a newline is encountered,
  • an EOF is encountered,
  • or, optionally, until the character delim is read. The delim character is not put into buffer.

Related topics:
get(), read()

good

Syntax:
  bool good();

The function good() returns true if no errors have occurred with the current stream, false otherwise.

Related topics:
bad(), fail(), eof(), clear(), rdstate()

ignore

Syntax:
  istream &ignore( streamsize num=1, int delim=EOF );

The ignore() function is used with input streams. It reads and throws away characters until num characters have been read (defaults to 1) or until the character delim is read (which defaults to EOF).

Related topics:
get(), getline()

open

Syntax:
  void open( const char *filename );
  void open( const char *filename, openmode mode );

The function open() is used with file streams. It opens filename and associates it with the current stream. The optional mode can be:

Mode | Meaning
ios::app | append output
ios::ate | seek to EOF when opened
ios::binary | open the file in binary mode
ios::in | open the file for reading
ios::out | open the file for writing
ios::trunc | overwrite the existing file

If open() fails, the resulting stream will evaluate to false when used in a Boolean expression. For example:

  ifstream inputStream("file.txt");
  if( !inputStream ) {
    cerr << "Error opening input stream" << endl;
    return;
  }
Related topics:
close(), fstream(), ifstream(), ofstream(),

peek

Syntax:
  int peek();

The function peek() is used with input streams, and returns the next character in the stream or EOF if the end of file is read. peek() does not remove the character from the stream.

Related topics:
get(), putback()

precision

Syntax:
  streamsize precision();
  streamsize precision( streamsize p );

The precision() function either sets or returns the current number of digits that is displayed for floating-point variables. For example, the following code:

    float num = 314.15926535;
    cout.precision( 5 );
    cout << num;

displays

    314.16
Related topics:
width(), fill()

put

Syntax:
  ostream &put( char ch );

The function put() is used with output streams, and writes the character ch to the stream.

Related topics:
write(), get()

putback

Syntax:
  istream &putback( char ch );

The putback() function is used with input streams, and returns the previously-read character ch to the input stream.

Related topics:
peek()

rdstate

Syntax:
  iostate rdstate();

The rdstate() function returns the status of the current stream. The iostate object has the these flags:

Flag | Meaning
badbit | a fatal error has occurred
eofbit | EOF has been found
failbit | a nonfatal error has occurred
goodbit | no errors have occurred

Related topics:
eof(), good(), bad(), clear(), fail()

read

Syntax:
  istream &read( char *buffer, streamsize num );

The function read() is used with input streams, and reads num bytes from the stream before placing them in buffer. If EOF is encountered, read() stops, leaving however many bytes it put into buffer as they are. For example:

    struct {
      int height;
      int width;
    } rectangle;

    input_file.read( (char *)(&rectangle), sizeof(rectangle) );
    if( input_file.bad() ) {
      cerr << "Error reading data" << endl;
      exit( 0 );
    }
Related topics:
gcount(), get(), getline(), write()

seekg

Syntax:
  istream &seekg( off_type offset, ios::seekdir origin );
  istream &seekg( pos_type position );

The function seekg() is used with input streams, and it repositions the "get" pointer for the current stream to offset bytes away from origin, or places the "get" pointer at position.

Related topics:
seekp(), tellg(), tellp()

seekp

Syntax:
  ostream &seekp( off_type offset, ios::seekdir origin );
  ostream &seekp( pos_type position );

The seekp() function is used with output streams, but is otherwise very similar to seekg().

Related topics:
seekg(), tellg(), tellp()

setf

Syntax:
  fmtflags setf( fmtflags flags );
  fmtflags setf( fmtflags flags, fmtflags needed );

The function setf() sets the formatting flags of the current stream to flags. The optional needed lets only the flags that are in both flags and needed be set. The return value is the previous configuration of flags. For example:

    int number = 0x3FF;
    cout.setf( ios::dec );
    cout << "Decimal: " << number << endl;
    cout.unsetf( ios::dec );
    cout.setf( ios::hex );
    cout << "Hexadecimal: " << number << endl;

Note that the preceding code is functionally identical to:

    int number = 0x3FF;
    cout << "Decimal: " << number << endl << hex << "Hexadecimal: " << number << dec << endl;

thanks to manipulators.

Related topics:
flags(), unsetf()

sync_with_stdio

Syntax:
  static bool sync_with_stdio( bool sync=true );

The sync_with_stdio() function allows you to turn on and off the ability for the C++ I/O system to work with the C I/O system.

tellg

Syntax:
  pos_type tellg();

The tellg() function is used with input streams, and returns the current "get" position of the pointer in the stream.

Related topics:
seekg(), seekp(), tellp()

tellp

Syntax:
  pos_type tellp();

The tellp() function is used with output streams, and returns the current "put" position of the pointer in the stream. For example, the following code displays the file pointer as it writes to a stream:

  string s("In Xanadu did Kubla Khan...");
  ofstream fout("output.txt");
  for( int i=0; i < s.length(); i++ ) {
    cout << "File pointer: " << fout.tellp();
    fout.put( s[i] );
    cout << " " << s[i] << endl;
  }
  fout.close();
Related topics:
seekg(), seekp(), tellg()

unsetf

Syntax:
  void unsetf( fmtflags flags );

The function unsetf() is used to clear the given flags associated with the current stream. What flags?

Related topics:
setf(), flags()

width

Syntax:
  int width();
  int width( int w );

The function width() returns the current width. The optional w can be used to set the width. Width is defined as the minimum number of characters to display with each output. For example:

    cout.width( 5 );
    cout << "2";

displays

        2

(that's four spaces followed by a '2')

Related topics:
precision(), fill()

write

Syntax:
  ostream &write( const char *buffer, streamsize num );

The write() function is used with output streams, and writes num bytes from buffer to the current output stream.

Related topics:
read(), put()


C++ I/O Flags

C++ defines some format flags for standard input and output, which can be manipulated with the flags(), setf(), and unsetf() functions. For example,

    cout.setf(ios::left);

turns on left justification for all output directed to cout.

Flag | Meaning
boolalpha | Boolean values can be input/output using the words "true" and "false".
dec | Numeric values are displayed in decimal.
fixed | Display floating point values using normal notation (as opposed to scientific).
hex | Numeric values are displayed in hexidecimal.
internal | If a numeric value is padded to fill a field, spaces are inserted between the sign and base character.
left | Output is left justified.
oct | Numeric values are displayed in octal.
right | Output is right justified.
scientific | Display floating point values using scientific notation.
showbase | Display the base of all numeric values.
showpoint | Display a decimal and extra zeros, even when not needed.
showpos | Display a leading plus sign before positive numeric values.
skipws | Discard whitespace characters (spaces, tabs, newlines) when reading from a stream.
unitbuf | Flush the buffer after each insertion.
uppercase | Display the "e" of scientific notation and the "x" of hexidecimal notation as capital letters.

You can also manipulate flags indirectly, using the following manipulators. Most programmers are familiar with the endl manipulator, which might give you an idea of how manipulators are used. For example, to set the dec flag, you might use the following command:

  cout << dec;

Manipulators defined in <iostream>
Manipulator | Description | Input | Output
boolalpha | Turns on the boolalpha flag | X | X
dec | Turns on the dec flag | X | X
endl | Output a newline character, flush the stream |  | X
ends | Output a null character |  | X
fixed | Turns on the fixed flag |  | X
flush | Flushes the stream |  | X
hex | Turns on the hex flag | X | X
internal | Turns on the internal flag |  | X
left | Turns on the left flag |  | X
noboolalpha | Turns off the boolalpha flag | X | X
noshowbase | Turns off the showbase flag |  | X
noshowpoint | Turns off the showpoint flag |  | X
noshowpos | Turns off the showpos flag |  | X
noskipws | Turns off the skipws flag | X |
nounitbuf | Turns off the unitbuf flag |  | X
nouppercase | Turns off the uppercase flag |  | X
oct | Turns on the oct flag | X | X
right | Turns on the right flag |  | X
scientific | Turns on the scientific flag |  | X
showbase | Turns on the showbase flag |  | X
showpoint | Turns on the showpoint flag |  | X
showpos | Turns on the showpos flag |  | X
skipws | Turns on the skipws flag | X |
unitbuf | Turns on the unitbuf flag |  | X
uppercase | Turns on the uppercase flag |  | X
ws | Skip any leading whitespace | X |
Manipulators defined in <iomanip>
Manipulator | Description | Input | Output
resetiosflags( long f ) | Turn off the flags specified by f | X | X
setbase( int base ) | Sets the number base to base |  | X
setfill( int ch ) | Sets the fill character to ch |  | X
setiosflags( long f ) | Turn on the flags specified by f | X | X
setprecision( int p ) | Sets the number of digits of precision |  | X
setw( int w ) | Sets the field width to w |  | X


C++ Strings

Constructors | methods to initialize strings
Operators | compare and assign strings
append() | adds text to the end of a string
assign() | assigns text to a string
at() | returns characters at a given index
begin() | returns an iterator to the first element of the string
c_str() | returns a standard C character array version of the string
capacity() | the number of characters the string can hold
clear() | clears the string
compare() | compares two strings
copy() | copies characters into an array
data() | returns a pointer to the first character
empty() | true if the string is empty
end() | returns an iterator to the end of the string
erase() | remove parts of the string
find() | find characters in the string
find_first_of() | find first occurrence of characters
find_first_not_of() | find first absence of characters
find_last_of() | find last occurrence of characters
find_last_not_of() | find last absence of characters
get_allocator() | returns the string's allocator
insert() | insert characters into the string
length() | returns the string's length
max_size() | returns the maximum number of characters that the string can hold
rbegin() | returns a reverse iterator to the end of the string
rend() | returns a reverse iterator to the beginning of the string
replace() | replace characters in the string
reserve() | sets the capacity of the string
resize() | change the size of the string
rfind() | find the last occurrence of a substring
size() | returns the number of characters in the string
substr() | returns a certain substring
swap() | exchange two strings


C++ Strings

Constructors

Syntax:
  string();
  string( size_type length, char ch );
  string( const char *str );
  string( const char *str, size_type length );
  string( string &str, size_type index, size_type length );
  string( input_iterator start, input_iterator end );

The string constructors create a new string containing:

  • length copies of ch,
  • a duplicate of str (optionally up to length characters long),
  • a substring of str starting at index and length characters long, or
  • elements from start to end.
For example,

    string str1( 5, 'c' );
    string str2( "Now is the time..." );
    string str3( str2, 11, 4 );
    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;

displays

    ccccc
    Now is the time...
    time

Operators

Syntax:
  ==
  >
  <
  >=
  <=
  !=
  +
  +=
  []

You can compare strings with ==, >, <, >=, <=, and !=. You can combine two strings with the + operator or the += operator, and look at a specific character with the [] operator.

Related topics:
at(), compare().

append

Syntax:
  basic_string &append( const basic_string &str );
  basic_string &append( const char *str );
  basic_string &append( const basic_string &str, size_type index, size_type len );
  basic_string &append( const char *str, size_type num );
  basic_string &append( size_type num, char ch );
  basic_string &append( input_iterator start, input_iterator end );

The append() function either:

  • appends str on to the end of the current string,
  • appends a substring of str starting at index that is len characters long on to the end of the current string,
  • appends num characters of str on to the end of the current string,
  • appends num repititions of ch on to the end of the current string,
  • or appends the sequence denoted by start and end on to the end of the current string.
For example, the following code:

    string str = "Hello World";
    str.append( 10, '!' );
    cout << str << endl;

displays

    Hello World!!!!!!!!!!
Related topics:
The + operator

assign

Syntax:
  basic_string &assign( const basic_string &str );
  basic_string &assign( const char *str );
  basic_string &assign( const char *str, size_type num );
  basic_string &assign( const basic_string &str, size_type index, size_type len );
  basic_string &assign( size_type num, char ch );

The function assign either:

  • assigns str to the current string,
  • assigns the first num characters of str to the current string,
  • assigns a substring of str starting at index that is len characters long to the current string,
  • or assigns num reptitions of ch to the current string.
For example, the following code:

    string str1, str2 = "War and Peace";
    str1.assign( str2, 4, 3 );
    cout << str1 << endl;

displays

    and

at

Syntax:
  reference at( size_type index );

The at() function returns a reference to the character at location index. If index is not within the string, then at() reports an out of range error by throwing an object of the out_of_range class. For example, this code:

    string text = "ABCDEF";
    char ch = text.at( 2 );

displays the character 'C'.

Related topics:
The [] operator

begin

Syntax:
  iterator begin();

The begin() function returns an iterator to the first element of the current string.

Related topics:
end()

c_str

Syntax:
  const char *c_str();

The function c_str() returns a pointer to a regular C string, identical to the current string.

Related topics:
The [] operator

capacity

Syntax:
  size_type capacity();

The capacity() function returns the number of characters that the current string can hold before it will need to allocate more memory. This number will be at least as large as size().

Related topics:
max_size(), reserve(), resize(), size(),

clear

Syntax:
  void clear();

The clear() function clears the string of all characters, effectively calling erase( begin(), end() ).

Related topics:
erase()

compare

Syntax:
  int compare( const basic_string &str );
  int compare( const char *str );
  int compare( size_type index, size_type length, const basic_string &str );
  int compare( size_type index, size_type length, const basic_string &str, size_type index2,
  size_type length2 );
  int compare( size_type index, size_type length, const char *str, size_type length2 );

The compare() function either compares str to the current string in a variety of ways, returning

Return Value | Case
less than zero | this < str
zero | this == str
greater than zero | this > str

The various functions either:

  • compare str to the current string,
  • compare str to a substring of the current string,starting at index for length characters,
  • compare a substring of str to a substring of the current string, where index2 and length2 refer to str and index and length refer to the current string,
  • or compare a substring of str to a substring of the current string, where the substring of str begins at zero and is length2 characters long, and the substring of the current string begins at index and is length characters long.

Related topics:
Operators

copy

Syntax:
  size_type copy( char *str, size_type num, size_type index );

The copy() function copies num characters of the current string (starting at index) into str. The return value is the number of characters copied.

data

Syntax:
  const char *data();

The function data() returns a pointer to the first character in the current string.

Related topics:
c_str()

empty

Syntax:
  bool empty();

The empty() function returns true if the current string is empty, and false otherwise.

end

Syntax:
  iterator end();

The end() function returns an iterator to the end of the string.

Related topics:
begin()

erase

Syntax:
  iterator erase( iterator pos );
  iterator erase( iterator start, iterator end );
  basic_string &erase( size_type index = 0, size_type num = npos );

The erase() function either:

  • removes the character pointed to by pos, returning an iterator to the next character,
  • removes the characters between start and end, returning an iterator to the character after the last character removed,
  • or removes num characters from the current string, starting at index, and returns *this.
The parameters index and num have default values, which means that erase() can be called with just index to erase all characters after index or with no arguments to erase all characters. For example:

    string s("So, you like donuts, eh? Well, have all the donuts in the world!");
    cout << "The original string is '" << s << "'" << endl;

    s.erase( 50, 14 );
    cout << "Now the string is '" << s << "'" << endl;
    s.erase( 24 );
    cout << "Now the string is '" << s << "'" << endl;
    s.erase();
    cout << "Now the string is '" << s << "'" << endl;

will display

    The original string is 'So, you like donuts, eh? Well, have all the donuts in the world!'
    Now the string is 'So, you like donuts, eh? Well, have all the donuts'
    Now the string is 'So, you like donuts, eh?'
    Now the string is ''
Related topics:
clear()

find

Syntax:
  size_type find( const basic_string &str, size_type index );
  size_type find( const char *str, size_type index );
  size_type find( const char *str, size_type index, size_type length );
  size_type find( char ch, size_type index );

The function find() either:

  • returns the first occurrence of str within the current string, starting at index, string::npos if nothing is found,
  • returns the first occurrence of str within the current string and within length characters, starting at index, string::npos if nothing is found,
  • or returns the index of the first occurrence ch within the current string, starting at index, string::npos if nothing is found.
For example,

    string str1( "Alpha Beta Gamma Delta" );
    unsigned int loc = str1.find( "Omega", 0 );
    if( loc != string::npos )
      cout << "Found Omega at " << loc << endl;
    else
      cout << "Didn't find Omega" << endl;

find_first_of

Syntax:
  size_type find_first_of( const basic_string &str, size_type index = 0 );
  size_type find_first_of( const char *str, size_type index = 0 );
  size_type find_first_of( const char *str, size_type index, size_type num );
  size_type find_first_of( char ch, size_type index = 0 );

The find_first_of() function either:

  • returns the index of the first character within the current string that matches any character in str, beginning the search at index, string::npos if nothing is found,
  • returns the index of the first character within the current string that matches any character in str, beginning the search at index and searching at most num characters, string::npos if nothing is found,
  • or returns the index of the first occurrence of ch in the current string, starting the search at index, string::npos if nothing is found.

Related topics:
find()

find_first_not_of

Syntax:
  size_type find_first_not_of( const basic_string &str, size_type index = 0 );
  size_type find_first_not_of( const char *str, size_type index = 0 );
  size_type find_first_not_of( const char *str, size_type index, size_type num );
  size_type find_first_not_of( char ch, size_type index = 0 );

The find_first_not_of() function either:

  • returns the index of the first character within the current string that does not match any character in str, beginning the search at index, string::npos if nothing is found,
  • returns the index of the first character within the current string that does not match any character in str, beginning the search at index and searching at most num characters, string::npos if nothing is found,
  • or returns the index of the first occurrence of a character that does not match ch in the current string, starting the search at index, string::npos if nothing is found.

Related topics:
find()

find_last_of

Syntax:
  size_type find_last_of( const basic_string &str, size_type index = npos );
  size_type find_last_of( const char *str, size_type index = npos );
  size_type find_last_of( const char *str, size_type index, size_type num );
  size_type find_last_of( char ch, size_type index = npos );

The find_last_of() function either:

  • returns the index of the first character within the current string that matches any character in str, doing a reverse search from index, string::npos if nothing is found,
  • returns the index of the first character within the current string that matches any character in str, doing a reverse search from index and searching at most num characters, string::npos if nothing is found,
  • or returns the index of the first occurrence of ch in the current string, doing a reverse search from index, string::npos if nothing is found.

Related topics:
find()

find_last_not_of

Syntax:
  size_type find_last_not_of( const basic_string &str, size_type index = npos );
  size_type find_last_not_of( const char *str, size_type index = npos);
  size_type find_last_not_of( const char *str, size_type index, size_type num );
  size_type find_last_not_of( char ch, size_type index = npos );

The find_last_not_of() function either:

  • returns the index of the first character within the current string that does not match any character in str, doing a reverse search from index, string::npos if nothing is found,
  • returns the index of the first character within the current string that does not match any character in str, doing a reverse search from index and searching at most num characters, string::npos if nothing is found,
  • or returns the index of the first occurrence of a character that does not match ch in the current string, doing a reverse search from index, string::npos if nothing is found.

Related topics:
find()

get_allocator

Syntax:
  allocator_type get_allocator();

The function get_allocator() returns the allocator for the current string.

insert

Syntax:
  iterator insert( iterator i, const char &ch );
  basic_string &insert( size_type index, const basic_string &str );
  basic_string &insert( size_type index, const char *str );
  basic_string &insert( size_type index1, const basic_string &str, size_type index2, size_type num );
  basic_string &insert( size_type index, const char *str, size_type num );
  basic_string &insert( size_type index, size_type num, char ch );
  void insert( iterator i, size_type num, const char &ch );
  void insert( iterator i, iterator start, iterator end );

The very multi-purpose insert() function either:

  • inserts ch before the character denoted by i,
  • inserts str into the current string, at location index,
  • inserts a substring of str (starting at index2 and num characters long) into the current string, at location index1,
  • inserts num characters of str into the current string, at location index,
  • inserts num copies of ch into the current string, at location index,
  • inserts num copies of ch into the current string, before the character denoted by i,
  • or inserts the characters denoted by start and end into the current string, before the character specified by i.

Related topics:
replace()

length

Syntax:
  size_type length();

The function length() returns the length of the current string. This number should be the same as the one returned from size().

Related topics:
size()

max_size

Syntax:
  size_type max_size();

The max_size() function returns the maximum number of characters that the string can hold.

rbegin

Syntax:
  const reverse_iterator rbegin();

The function rbegin() returns a reverse iterator to the end of the current string.

Related topics:
rend()

rend

Syntax:
  const reverse_iterator rend();

The rend() function returns a reverse iterator to the start of the current string.

Related topics:
rbegin()

replace

Syntax:
  basic_string &replace( size_type index, size_type num, const basic_string &str );
  basic_string &replace( size_type index1, size_type num1, const basic_string &str, size_type index2,
  size_type num2 );
  basic_string &replace( size_type index, size_type num, const char *str );
  basic_string &replace( size_type index, size_type num1, const char *str, size_type num2 );
  basic_string &replace( size_type index, size_type num1, size_type num2, char ch );
  basic_string &replace( iterator start, iterator end, const basic_string &str );
  basic_string &replace( iterator start, iterator end, const char *str );
  basic_string &replace( iterator start, iterator end, const char *str, size_type num );
  basic_string &replace( iterator start, iterator end, size_type num, char ch );

The function replace() either:

  • replaces characters of the current string with up to num characters from str, beginning at index,
  • replaces up to num1 characters of the current string (starting at index1) with up to num2 characters from str beginning at index2,
  • replaces up to num characters of the current string with characters from str, beginning at index in str,
  • replaces up to num1 characters in the current string (beginning at index1) with num2 characters from str beginning at index2,
  • replaces up to num1 characters in the current string (beginning at index) with num2 copies of ch,
  • replaces the characters in the current string from start to end with str,
  • replaces characters in the current string from start to end with num characters from str,
  • or replaces the characters in the current string from start to end with num copies of ch.
For example, the following code displays the string "They say he carved it himself...find your soul-mate, Homer."
    string s = "They say he carved it himself...from a BIGGER spoon";
    string s2 = "find your soul-mate, Homer.";
    s.replace( 32, s2.length(), s2 );
    cout << s << endl;

Related topics:
insert()

reserve

Syntax:
  void reserve( size_type num );

The function reserve() sets the capacity() of the current string to at least num.

Related topics:
capacity()

resize

Syntax:
  void resize( size_type num );
  void resize( size_type num, char ch );

The resize() function changes the size of the current string to num, optionally padding any new space with copies of ch.

rfind

Syntax:
  size_type rfind( const basic_string &str, size_type index );
  size_type rfind( const char *str, size_type index );
  size_type rfind( const char *str, size_type index, size_type num );
  size_type rfind( char ch, size_type index );

The rfind() function either:

  • returns the location of the first occurrence of str in the current string, doing a reverse search from index, string::npos if nothing is found,
  • returns the location of the first occurrence of str in the current string, doing a reverse search from index, searching at most num characters, string::npos if nothing is found,
  • or returns the location of the first occurrence of of ch in the current string, doing a recerse search from index, string::npos if nothing is found.
For example, in the following code, the first call to rfind() returns string::npos, because the target word is not within the first 8 characters of the string. However, the second call returns 9, because the target word is within 20 characters of the beginning of the string.
    int loc;
    string s = "My cat's breath smells like cat food.";
    loc = s.rfind( "breath", 8 );
    cout << "The word breath is at index " << loc << endl;
    loc = s.rfind( "breath", 20 );
    cout << "The word breath is at index " << loc << endl;

Related topics:
find()

size

Syntax:
  size_type size();

The size() function returns the number of characters currently in the string.

Related topics:
length(), max_size()

substr

Syntax:
  basic_string substr( size_type index, size_type num = npos );

The substr() function returns a substring of the current string, starting at index, and num characters long. If num is omitted, it will default to string::npos, and the substr() function will simply return the remainder of the string starting at index. For example:

    string s("What we have here is a failure to communicate");
    string sub = s.substr(21);
    cout << "The original string is " << s << endl;
    cout << "The substring is " << sub << endl;

displays

    The original string is What we have here is a failure to communicate
    The substring is a failure to communicate

swap

Syntax:
  void swap( basic_string &str );

The function swap() switches str with the current string. For example:

    string first( "This comes first" );
    string second( "And this is second" );
    first.swap( second );
    cout << first << endl;
    cout << second << endl;

displays

    And this is second
    This comes first


C++ Standard Template Library

The C++ STL (Standard Template Library) is a generic collection of class templates and algorithms that allow programmers to easily implement standard data structures like queues, lists, and stacks.

The C++ STL provides programmers with the following constructs, grouped into three categories:

  • Sequences
    • C++ Vectors
    • C++ Lists
    • C++ Double-Ended Queues
  • Container Adapters
    • C++ Stacks
    • C++ Queues
    • C++ Priority Queues
  • Associative Containers
    • C++ Bitsets
    • C++ Maps
    • C++ Multimaps
    • C++ Sets
    • C++ Multisets

The idea behind the C++ STL is that the hard part of using complex data structures has already been completed. If a programmer would like to use a stack of integers, all that she has to do is use this code:

stack<int> myStack;

With minimal effort, she can now push() and pop() integers onto this stack. Through the magic of C++ Templates, she could specify any data type, not just integers. The STL Stack class will provide generic functionality of a stack, regardless of the data in the stack.


C++ Bitsets

C++ Bitsets give the programmer a set of bits as a data structure. Bitsets can be manipulated by various binary operators such as logical AND, OR, and so on.

Constructors | create new bitsets
Operators | compare and assign bitsets
any() | true if any bits are set
count() | how many bits are set
flip() | reverses the bitset
none() | true if no bits are set
reset() | clears bits
set() | sets bits
size() | number of bits that the bitset can hold
test() | state of a given bit
to_string() | string representation of the bitset
to_ulong() | integer representation of the bitset


C++ Bitsets

Constructors

Syntax:
  bitset();
  bitset( unsigned long val );

Bitsets can either be constructed with no arguments or with an unsigned long number val that will be converted into binary and inserted into the bitset. When creating bitsets, the number given in the place of the template determines how long the bitset is.

For example, the following code creates two bitsets and displays them:

  // create a bitset that is 8 bits long
  bitset<8> bs;
  // display that bitset
  for( int i = (int) bs.size()-1; i >= 0; i-- ) {
    cout << bs[i] << " ";
  }
  cout << endl;
  // create a bitset out of a number
  bitset<8> bs2( (long) 131 );
  // display that bitset, too
  for( int i = (int) bs2.size()-1; i >= 0; i-- ) {
    cout << bs2[i] << " ";
  }
  cout << endl;

Operators

Syntax:
  !=, ==, &=, ^=, |=, ~, <<=, >>=, []

These operators all work with bitsets. They can be described as follows:

  • != returns true if the two bitsets are not equal.
  • == returns true if the two bitsets are equal.
  • &= performs the AND operation on the two bitsets.
  • ^= performs the XOR operation on the two bitsets.
  • |= performs the OR operation on the two bitsets.
  • ~ reverses the bitset (same as calling flip())
  • <<= shifts the bitset to the left
  • >>= shifts the bitset to the right
  • [x] returns a reference to the xth bit in the bitset.

For example, the following code creates a bitset and shifts it to the left 4 places:

  // create a bitset out of a number
  bitset<8> bs2( (long) 131 );
  cout << "bs2 is " << bs2 << endl;
  // shift the bitset to the left by 4 digits
  bs2 <<= 4;
  cout << "now bs2 is " << bs2 << endl;

When the above code is run, it displays:

  bs2 is 10000011
  now bs2 is 00110000

any

Syntax:
  bool any();

The any() function returns true if any bit of the bitset is 1, otherwise, it returns false.

count

Syntax:
  size_type count();

The function count() returns the number of bits that are set to 1 in the bitset.

flip

Syntax:
  bitset<N> &flip();
  bitset<N> &flip( size_t pos );

The flip() function inverts all of the bits in the bitset, and returns the bitset. If pos is specified, only the bit at position pos is flipped.

Related topics:
~ operator

none

Syntax:
  bool none();

The none() function only returns true if none of the bits in the bitset are set to 1.

reset

Syntax:
  bitset<N> &reset();
  bitset<N> &reset( size_t pos );

The reset() fucntion clears all of the bits in the bitset, and returns the bitset. If pos is specified, then only the bit at position pos is cleared.

set

Syntax:
  bitset<N> &set();
  bitset<N> &set( size_t pos, int val=1 );

The set() fucntion sets all of the bits in the bitset, and returns the bitset. If pos is specified, then only the bit at position pos is set.

size

Syntax:
  size_t size();

The size() function returns the number of bits that the bitset can hold.

test

Syntax:
  bool test( size_t pos );

The function test() returns the value of the bit at position pos.

to_string

Syntax:
  string to_string();

The to_string() function returns a string representation of the bitset.

to_ulong

Syntax:
  unsigned long to_ulong();

The function to_ulong() returns the bitset, converted into an unsigned long integer.


C++ Double-Ended Queues

cppreference.com -> C++ Double-Ended Queues

C++ Double Ended Queues

Double-ended queues are like vectors, except that they allow fast insertions and deletions at the beginning (as well as the end) of the container.

Constructors | create new deques
Operators | compare and assign deques
assign() | set the values of the deque
at() | returns a specific element
back() | returns the last element
begin() | returns an iterator to the first element
clear() | remove all elements
empty() | true if the deque is empty
end() | returns an iterator to the end of the queue
erase() | removes an element
front() | returns the first element
get_allocator() | returns the deque's allocator
insert() | insert elements into the deque
max_size() | returns the maximum elements that the deque can hold
pop_back() | removes the last element
pop_front() | removes the first element
push_back() | add an element to the end of the deque
push_front() | add an element to the front of the deque
rbegin() | returns a reverse iterator to the end of the deque
rend() | returns a reverse iterator to the beginning of the deque
resize() | change the size of the deque
size() | return the number of elements in the deque
swap() | swap one deque with another


C++ Double-Ended Queues

Constructors

Syntax:
  deque();
  deque( size_type size );
  deque( size_type num, const TYPE &val );
  deque( const deque &from );
  deque( input_iterator start, input_iterator end );

C++ Deques can be constructed with either:

  • Nothing - which creates an empty deque,
  • size - creates a deque of size num,
  • num and val - puts num copies of val in the deque,
  • from - creates a deque with the same contents as from, or
  • start and end - which creates a deque containing elements from start to end.

For example, the following code creates and displays a deque:

  // create a deque with ten '1's in it
  deque<int> dq( 10, 1 );
  // create an iterator
  deque<int>::iterator iter;
  // display the contents of our deque
  for( iter = dq.begin(); iter != dq.end(); iter++ ){
    cout << *iter << endl;
  }

Operators

Syntax:
  []

You can access individual members of the double-ended queue using the [] operator.

assign

Syntax:
  void assign( input_iterator start, input_iterator end);
  void assign( Size num, const TYPE &val );

The function assign() sets the double-ended queue the sequence denoted by start and end, or sets num elements to val.

at

Syntax:
  reference at( size_type pos );

The at() function returns a reference to the element at pos in the double-ended queue.

back

Syntax:
  reference back();

The function back() returns a reference to the back element of the double-ended queue.

begin

Syntax:
  iterator begin();

The begin() function returns an iterator to the front element of the double-ended queue.

clear

Syntax:
  void clear();

The clear() function deletes all of the elements from the double-ended queue.

empty

Syntax:
  bool empty();

The function empty() returns true if the double-ended queue is empty, and false otherwise.

end

Syntax:
  iterator end();

The end() function returns an iterator to the back of the double-ended queue.

erase

Syntax:
  iterator erase( iterator pos );
  iterator erase( iterator start, iterator end );

The function erase() erases the element at location pos, or the items between start and end. The return value is an iterator to the element just after the last one erased.

front

Syntax:
  reference front();

The front() function returns a reference to the element at the beginning of the double-ended queue.

get_allocator

Syntax:
  allocator_type get_allocator();

The get_allocator() function returns the double-ended queue's allocator.

insert

Syntax:
  iterator insert( iterator pos, size_type num, const TYPE &val );
  void insert( iterator pos, input_iterator start, input_iterator end );

The insert() function inserts num copies of val before the element at pos, or inserts the sequence specified by start and end before the element at pos.

max_size

Syntax:
  size_type max_size();

The function max_size() returns the maximum number of items that the double-ended queue can hold.

pop_back

Syntax:
  void pop_back();

The pop_back() function removes the last element from the double-ended queue.

pop_front

Syntax:
  void pop_front();

The function pop_front() removes the first element from the double-ended queue.

push_back

Syntax:
  void push_back( const TYPE &val );

The push_back() function adds val to the end of the double-ended queue.

push_front

Syntax:
  void push_front( const TYPE &val );

The function push_front() adds val to the front of the double-ended queue.

rbegin

Syntax:
  reverse_iterator rbegin();

The rbegin() function returns a reverse iterator to the back of the double-ended queue.

rend

Syntax:
  reverse_iterator rend();

The function rend() returns a reverse iterator to the front of the double-ended queue.

resize

Syntax:
  void resize( size_type num, TYPE val );

The resize() function changes the size of the double-ended queue to num, padding any added entries with elements equal to val.

size

Syntax:
  size_type size();

The size() function returns the number of elements in the double-ended queue.

swap

Syntax:
  void swap( deque &target );

The swap() function swaps the elements in the current double-ended queue with those in target.


C++ Lists

Lists are sequences of elements stored in a linked list. Compared to vectors, they allow fast insertions and deletions, but slower random access.

assign() | assign a sequence to the list
back() | returns the last element
begin() | returns an iterator to the beginning
clear() | removes all elements
empty() | true if the list is empty
end() | returns an iterator to the end
erase() | erase an element
front() | returns the first element
get_allocator() | returns the list's allocator
insert() | insert elements into the list
max_size() | returns the maximum number of elements the list can hold
merge() | merge two lists
pop_back() | removes the last element
pop_front() | removes the first element
push_back() | add an element to the end of the list
push_front() | add an element to the front of the list
rbegin() | returns a reverse iterator to the beginning of the list
remove() | removes elements from the list
remove_if() | removes elements conditionally
rend() | returns a reverse iterator to the start of the list
resize() | change the size of the list
reverse() | reverse the list
size() | the number the elements in the list
sort() | sorts the list
splice() | merge two lists
swap() | exchange two lists
unique() | removes duplicate elements


C++ Lists

assign

Syntax:
  void assign( input_iterator start, input_iterator end );
  void assign( size_type num, const TYPE &val );

The assign() function either sets the list to the sequence start to end, or assigns the list num elements of type val.

Related topics:
insert(),

back

Syntax:
  reference back();

The function back() returns a reference to the last element of the list.

Related topics:
front(), pop_back(),

begin

Syntax:
  iterator begin();

The function begin() returns an iterator to the first element of the list. For example,

    // Create a list of characters
    list<char> charList;
    for( int i=0; i < 10; i++ )
      charList.push_front( i + 65 );
    // Display the list
    list<char>::iterator theIterator;
    for( theIterator = charList.begin(); theIterator != charList.end(); theIterator++ )
      cout << *theIterator;

Related topics:
end(),

clear

Syntax:
  void clear();

The clear() function deletes all elements from the list.

empty

Syntax:
  bool empty();

The function empty() returns true if the list is empty, and false otherwise. For example:

    list<int> the_list;
    for( int i = 0; i < 10; i++ )
      the_list.push_back( i );
    while( !the_list.empty() ) {
      cout << the_list.front() << endl;
      the_list.pop_front();
    }

end

Syntax:
  iterator end();

The end() function returns an iterator the the end of the list.

Related topics:
begin(),

erase

Syntax:
  iterator erase( iterator pos );
  iterator erase( iterator start, iterator end );

The erase() function removes the element at location pos, or removes the elements between start and end. The return value is an iterator to the element after the last element that we removed.

front

Syntax:
  reference front();

The function front() returns a reference to the first element of the list.

    list<int> the_list;
    for( int i = 0; i < 10; i++ )
      the_list.push_back( i );
    while( !the_list.empty() ) {
      cout << the_list.front() << endl;
      the_list.pop_front();
    }
Related topics:
back(),

get_allocator

Syntax:
  allocator_type get_allocator();

The function get_allocator() returns the allocator for the list.

insert

Syntax:
  iterator insert( iterator pos, const TYPE &val );
  void insert( iterator pos, size_type num, const TYPE &val );
  void insert( iterator pos, input_iterator start, input_iterator end );

The insert() function either inserts val before the element at pos, inserts num copies of val before the element at pos, or inserts the sequence denoted by start and end before the element at pos. The return value is an iterator to the inserted element.

max_size

Syntax:
  size_type max_size();

The function max_size() returns the maximum number of elements that the list can hold.

merge

Syntax:
  void merge( list &lst );
  void merge( list &lst, Comp compfunction );

The function merge() merges the list with lst, producing a combined lists that is in order. If compfunction is specified, then it is used as the comparison function for the lists.

pop_back

Syntax:
  void pop_back();

The pop_back() function removes the last element of the list.

Related topics:
pop_front(),

pop_front

Syntax:
  void pop_front();

The function pop_front() removes the first element of the list.

Related topics:
pop_back(),

push_back

Syntax:
  void push_back( const TYPE &val );

The push_back() function appends val to the end of the list. For example:

    list<int> the_list;
    for( int i = 0; i < 10; i++ )
      the_list.push_back( i );
Related topics:
push_front(),

push_front

Syntax:
  void push_front( const TYPE &val );

The push_front() function inserts val at the beginning of the list.

Related topics:
push_back(),

rbegin

Syntax:
  reverse_iterator rbegin();

The function rbegin() returns a reverse iterator to the end of the list.

Related topics:
rend(),

remove

Syntax:
  void remove( const TYPE &val );

The function remove() removes all elements that are equal to val from the list. Fpr example,

    // Create a list that has the first 10 letters of the alphabet
    list<char> charList;
    for( int i=0; i < 10; i++ )
      charList.push_front( i + 65 );
    // Remove all instances of 'E'
    charList.remove( 'E' );

remove_if

Syntax:
  void remove_if( UnPred pr );

The remove_if() function removes all elements from the list for which the unary predicate pr is true.

rend

Syntax:
  reverse_iterator rend();

The function rend() returns a reverse iterator to the beginning of the list.

resize

Syntax:
  void resize( size_type num, TYPE val );

The function resize() changes the size of the list to num. Any elements that are added as padding will have the value val.

reverse

Syntax:
  void reverse();

The function reverse() reverses the list.

size

Syntax:
  size_type size();

The size() function returns the number of elements in the list.

sort

Syntax:
  void sort();
  void sort( Comp compfunction );

The sort() function sorts the lists, optionally using compfunction as the comparison function to determine if an element is less than another.

splice

Syntax:
  void splice( iterator pos, list<T,Allocator> &lst );
  void splice( iterator pos, list<T,Allocator> &lst, iterator del );
  void splice( iterator pos, list<T,Allocator> &lst, iterator start, iterator end );

The splice() function inserts lst at location pos. If specified, the element(s) at del or from start to end are removed.

swap

Syntax:
  void swap( list &lst );

The swap() function exchanges the elements in lst with those in the current list.

unique

Syntax:
  void unique();
  void unique( BinPred pr );

The function unique() removes all duplicate elements from the list. If pr is specified, then it is used to determine uniqueness.


C++ Maps

C++ Maps are associative containers that contain key/value pairs.

Operators | valid operators for maps
begin() | returns an iterator to the beginning of the map
clear() | removes all elements
count() | returns the number of times an element occurs
empty() | true if the map is empty
end() | returns an iterator to the end of the map
equal_range() | returns iterators to specific items
erase() | removes an element
find() | finds an element
get_allocator() | returns the map's allocator
insert() | inserts elements
key_comp() | returns the function that compares elements
lower_bound() | returns the first element greater than a certian value
max_size() | returns the maximum number of elements
rbegin() | returns a reverse iterator to the end of the map
rend() | returns a reverse iterator to the beginning of the map
size() | returns the number of elements in the map
swap() | swap two maps
upper_bound() | returns the first element greater than a certian value
value_comp() | returns the function that compares elements


C++ Maps

C++ Maps can be used to store key/value pairs.

Operators

Syntax:
  ==
  !=
  <
  >
  <=
  >=
  []

Valid operators for C++ maps include the comparison operators ==,!=,<,>,<=, and >= as well as the accessor operator [].

begin

Syntax:
  iterator begin();

The function begin() returns an iterator to the first element in the map.

clear

Syntax:
  void clear();

The clear() function deletes all elements from the map.

count

Syntax:
  size_type count( const KEY_TYPE &key );

The function count() returns the number of occurrences of key in the map.

empty

Syntax:
  bool empty();

The function empty() returns true if the map is empty, and false otherwise.

end

Syntax:
  iterator end();

The end() function returns an iterator to the end of the map.

equal_range

Syntax:
  pair<iterator, iterator> equal_range( const KEY_TYPE &key );

The function equal_range() looks at a sorted version of the map and returns two iterators - one to the first element that contains key, another just past the last element that contains key. If key is not in the map, the two iterators will be equal.

erase

Syntax:
  void erase( iterator pos );
  void erase( iterator start, iterator end );
  size_type erase( const KEY_TYPE &key );

The erase function() either erases the element at pos, erases the elements between start and end, or erases all elements that have the value of key.

find

Syntax:
  iterator find( const KEY_TYPE &key );

The find() function returns an iterator to key, or an iterator to the end of the map if key is not found.

get_allocator

Syntax:
  allocator_type get_allocator();

The get_allocator() function returns the allocator of the map.

insert

Syntax:
  iterator insert( iterator pos, const pair<KEY_TYPE,VALUE_TYPE> &val );
  void insert( input_iterator start, input_iterator end );
  pair<iterator, bool> insert( const pair<KEY_TYPE,VALUE_TYPE> &val );

The function insert() either:

  • inserts val after the element at pos, and returns an iterator to that element.
  • inserts a range of elements from start to end.
  • inserts val, but only if val doesn't already exist. The return value is an iterator to the element inserted, and a boolean describing whether an insertion took place.

key_comp

Syntax:
  key_compare key_comp();

The function key_comp() returns the function that compares keys.

lower_bound

Syntax:
  iterator lower_bound( const KEY_TYPE &key );

The lower_bound() function returns an iterator to the first element which has a value greater than or equal to key.

max_size

Syntax:
  size_type max_size();

The function max_size() returns the maximum number of elements that the map can hold.

rbegin

Syntax:
  reverse_iterator rbegin();

The rbegin() function returns a reverse iterator to the end of the map.

rend

Syntax:
  reverse_iterator rend();

The function rend() returns a reverse iterator to the start of the map.

size

Syntax:
  size_type size();

The function size() returns the number of elements currently in the map.

swap

Syntax:
  void swap( map<Key,T,Comp,Allocator> &obj );

The swap() function exchanges the elements in obj with those in the current map.

upper_bound

Syntax:
  iterator upper_bound( const KEY_TYPE &key );

The function upper_bound() returns an iterator to the first element in the map with a key greater than key.

value_comp

Syntax:
  value_compare value_comp();

The value_comp() function returns the function that compares values.


C++ MultiMaps

C++ Multimaps are like maps, but they allow duplicate keys.

begin() | returns an iterator to the first element
clear() | removes all elements
count() | number of times an element occurs
empty() | true if the multimap is empty
end() | returns an iterator to the last element
equal_range() | returns iterators to first and last occurances of elements
erase() | removes elements
find() | returns an iterator to an element
get_allocator() | returns the multimap's allocator
insert() | inserts elements
key_comp() | returns the function that compares keys
lower_bound() | returns an iterator to the first element greater than a certian value
max_size() | the maximum number of elements the multimap can hold
rbegin() | returns a reverse iterator to the end of the multimap
rend() | returns a reverse iterator to the beginning of the multimap
size() | the number of elements in the multimap
swap() | swaps two multimaps
upper_bound() | returns an iterator to the first element greater than a certian value
value_comp() | returns the function that compares elements


C++ Multimaps

begin

Syntax:
  iterator begin();

The function begin() returns an iterator to the first element in the multimap.

clear

Syntax:
  void clear();

The clear() function deletes all elements from the multimap.

count

Syntax:
  size_type count( const key_type &key );

The function count() returns the number of occurrences of key in the multimap.

empty

Syntax:
  bool empty();

The function empty() returns true if the multimap is empty, and false otherwise.

end

Syntax:
  iterator end();

The end() function returns an iterator to the end of the multimap.

equal_range

Syntax:
  pair<iterator, iterator> equal_range( const key_type &key );

The function equal_range() returns two iterators - one to the first element that contains key, another to the last element that contains key.

erase

Syntax:
  void erase( iterator pos );
  void erase( iterator start, iterator end );
  size_type erase( const key_type &key );

The erase function() either erases the element at pos, erases the elements between start and end, or erases all elements that have the value of key.

find

Syntax:
  iterator find( const key_type &key );

The find() function returns an iterator to key, or an iterator to the end of the multimap if key is not found.

get_allocator

Syntax:
  allocator_type get_allocator();

The get_allocator() function returns the allocator of the multimap.

insert

Syntax:
  iterator insert( iterator pos, const TYPE &val );
  void insert( input_iterator start, input_iterator end );
  pair<iterator, bool> insert( const TYPE &val );

The function insert() either:

  • inserts val after the element at pos, and returns an iterator to that element.
  • inserts a range of elements from start to end.
  • inserts val, but only if val doesn't already exist. The return value is an iterator to the element inserted, and a boolean describing whether an insertion took place.

key_comp

Syntax:
  key_compare key_comp();

The function key_comp() returns the function that compares keys.

lower_bound

Syntax:
  iterator lower_bound( const key_type &key );

The lower_bound() function returns an iterator to the first element which has a value greater than or equal to key.

max_size

Syntax:
  size_type max_size();

The function max_size() returns the maximum number of elements that the multimap can hold.

rbegin

Syntax:
  reverse_iterator rbegin();

The rbegin() function returns a reverse iterator to the end of the multimap.

rend

Syntax:
  reverse_iterator rend();

The function rend() returns a reverse iterator to the start of the multimap.

size

Syntax:
  size_type size();

The function size() returns the number of elements currently in the multimap.

swap

Syntax:
  void swap( multimap<Key,T,Comp,Allocator> &obj );

The swap() function exchanges the elements in obj with those in the current multimap.

upper_bound

Syntax:
  iterator upper_bound( const key_type &key );

The function upper_bound() returns an iterator to the first element in the multimap with a key greater than key.

value_comp

Syntax:
  value_compare value_comp();

The value_comp() function returns the function that compares values.


C++ MultiSets

C++ Multisets are like sets, but they allow duplicate objects.

begin() | returns an iterator to the first element
clear() | removes all elements
count() | returns the number of elements
empty() | true if the multiset is empty
end() | returns an iterator to the last element
equal_range() | returns iterators to the first and last elements matching a specific key
erase() | removes elements
find() | returns an iterator to specific elements
get_allocator() | returns the multiset's allocator
insert() | inserts elements into the multiset
key_comp() | returns the function that compares elements
lower_bound() | returns an iterator to the first element greater than a certian value
max_size() | returns the maximum number of elements
rbegin() | returns a reverse iterator to the end of the multiset
rend() | returns a reverse iterator to the beginning of the multiset
size() | number of elements in the multiset
swap() | swaps two multisets
upper_bound() | returns an iterator to the first element greater than a certain value
value_comp() | returns the function that compares elements


C++ Multisets

begin

Syntax:
  iterator begin();

The function begin() returns an iterator to the first element in the multiset.

clear

Syntax:
  void clear();

The clear() function deletes all elements from the multiset.

count

Syntax:
  size_type count( const key_type &key );

The function count() returns the number of occurrences of key in the multiset.

empty

Syntax:
  bool empty();

The function empty() returns true if the multiset is empty, and false otherwise.

end

Syntax:
  iterator end();

The end() function returns an iterator to the end of the multiset.

equal_range

Syntax:
  pair<iterator, iterator> equal_range( const key_type &key );

The function equal_range() returns two iterators - one to the first element that contains key, another to the last element that contains key.

erase

Syntax:
  void erase( iterator pos );
  void erase( iterator start, iterator end );
  size_type erase( const key_type &key );

The erase function() either erases the element at pos, erases the elements between start and end, or erases all elements that have the value of key.

find

Syntax:
  iterator find( const key_type &key );

The find() function returns an iterator to key, or an iterator to the end of the multiset if key is not found.

get_allocator

Syntax:
  allocator_type get_allocator();

The get_allocator() function returns the allocator of the multiset.

insert

Syntax:
  iterator insert( iterator pos, const TYPE &val );
  void insert( input_iterator start, input_iterator end );
  pair<iterator, bool> insert( const TYPE &val );

The function insert() either:

  • inserts val after the element at pos, and returns an iterator to that element.
  • inserts a range of elements from start to end.
  • inserts val, but only if val doesn't already exist. The return value is an iterator to the element inserted, and a boolean describing whether an insertion took place.

key_comp

Syntax:
  key_compare key_comp();

The function key_comp() returns the function that compares keys.

lower_bound

Syntax:
  iterator lower_bound( const key_type &key );

The lower_bound() function returns an iterator to the first element which has a value greater than or equal to key.

max_size

Syntax:
  size_type max_size();

The function max_size() returns the maximum number of elements that the multiset can hold.

rbegin

Syntax:
  reverse_iterator rbegin();

The rbegin() function returns a reverse iterator to the end of the multiset.

rend

Syntax:
  reverse_iterator rend();

The function rend() returns a reverse iterator to the start of the multiset.

size

Syntax:
  size_type size();

The function size() returns the number of elements currently in the multiset.

swap

Syntax:
  void swap( multiset<Key,Comp,Allocator> &obj );

The swap() function exchanges the elements in obj with those in the current multiset.

upper_bound

Syntax:
  iterator upper_bound( const key_type &key );

The function upper_bound() returns an iterator to the first element in the multiset with a key greater than key.

value_comp

Syntax:
  value_compare value_comp();

The value_comp() function returns the function that compares values.


C++ Priority Queues

C++ Priority Queues are like queues, but the elements inside the the data structure are ordered by some predicate.

empty() | true if the priority queue is empty
pop() | removes the first element
push() | adds an element
size() | returns the number of elements in the priority queue
top() | returns the value of the element with highest priority


C++ Priority Queues

empty

Syntax:
  bool empty();

The empty() function returns true if the current priority queue is empty, and false otherwise.

pop

Syntax:
  void pop();

The function pop() discards the first element in the current priority queue.

push

Syntax:
  void push( const TYPE &val );

The function push() adds an element to the current priority queue.

size

Syntax:
  size_type size();

The size() function returns the number of things in the current priority queue.

top

Syntax:
   TYPE &top();

The top() function returns a reference to the element in the queue with the highest priority. Note that only pop() removes an element.


C++ Queues

The C++ Queue is a container adapter that gives the programmer a FIFO (first-in, first-out) data structure.

back() | returns the last element
empty() | true if the queue is empty
front() | returns the first element
pop() | removes the first element
push() | adds an element to the end of the queue
size() | returns the number of elements in the queue


C++ Queues

back

Syntax:
   TYPE &back();

The function back() returns a reference to the last element in the current queue.

empty

Syntax:
  bool empty();

The empty() function returns true if the current queue is empty, and false otherwise.

front

Syntax:
   TYPE &front();

The function front() returns a reference to the first element in the current queue.

pop

Syntax:
  void pop();

The function pop() discards the first element in the current queue.

push

Syntax:
  void push( const TYPE &val );

The function push() adds an element to the current queue.

size

Syntax:
  size_type size();

The size() function returns the number of things in the current queue.


C++ Sets

The C++ Set is an associative container that contains an ordered set of objects.

begin() | returns an iterator to the first element
clear() | removes all elements
count() | returns the number of elements
empty() | true if the set is empty
end() | returns an iterator to the last element
equal_range() | returns iterators to the first and last elements that match a certain key
erase() | removes elements
find() | finds a given element
get_allocator() | returns the set's allocator
insert() | inserts elements into the set
lower_bound() | returns an iterator to the first element greater than a certain value
key_comp() | returns the function that compares keys
max_size() | the maximum number of elements that the set can hold
rbegin() | returns a reverse iterator to the end of the set
rend() | returns a reverse iterator to the beginning of the set
size() | the number of elements in the set
swap() | exchanges two sets
upper_bound() | returns an iterator to the first element greater than a certain value
value_comp() | returns the function that compares values


C++ Sets

begin

Syntax:
  iterator begin();

The begin() function returns an iterator to the first element of the current set.

clear

Syntax:
  void clear();

The clear() function removes all of the elements from the current set.

count

Syntax:
  size_type count( const key_type &key );

The function count() returns the number of occurances of key in the current set.

empty

Syntax:
  bool empty();

The empty() function returns true if the current set is empty, and false otherwise.

end

Syntax:
  const_iterator end();

The end() function returns an iterator to the end of the current set.

equal_range

Syntax:
  pair<iterator,iterator> equal_range( const key_type &key );

The function equal_range() finds the first and last locations of key in the current set, and returns iterators to those locations.

erase

Syntax:
  void erase( iterator i );
  void erase( iterator start, iterator end );
  size_type erase( const key_type &key );

The erase() function either:

  • erases the element at location i,
  • erases the elements from start to end, or
  • erases all elements that have a value of key (returning the number of elements erased).

find

Syntax:
  iterator find( const key_type &key );

The find() function attempts to find an element of the current set that matches key, then returns an iterator to that element. If no match is found, an iterator to the end of the set is returned.

get_allocator

Syntax:
  allocator_type get_allocator();

The get_allocator() function returns the allocator for the current set.

insert

Syntax:
  iterator insert( iterator i, const TYPE &val );
  void insert( input_iterator start, input_iterator end );
  pair<iterator,bool> insert( const TYPE &val );

The function insert() either:

  • inserts val after the element at i,
  • inserts a range of elements denoted by start and end, or
  • inserts val into the current set, returning an iterator and a boolean value indicating whether val was successfully inserted.
It should be noted that duplicate elements are not inserted into sets.

lower_bound

Syntax:
  iterator lower_bound( const key_type &key );

The function lower_bound() returns an iterator to the first element in the current set with a key equal to or greater than key.

key_comp

Syntax:
  key_compare key_comp();

The function key_comp() returns a function object that compares keys.

max_size

Syntax:
  size_type max_size();

The max_size() function returns the maximum number of elements that the current set can hold.

rbegin

Syntax:
  reverse_iterator rbegin();

The function rbegin() returns a reverse iterator to the end of the current set.

rend

Syntax:
  reverse_iterator rend();

The rend() function returns a reverse iterator to the beginning of the current set.

size

Syntax:
  size_type size();

The size() function returns the number of elements in the current set.

swap

Syntax:
  void swap( set<Key,Comp,Allocator> &object );

The function swap() exchanges the elements stored in the current set with those in object.

upper_bound

Syntax:
  iterator upper_bound( const key_type &key );

The upper_bound() function returns an iterator to the first element in the current set with a key greater than key.

value_comp

Syntax:
  value_compare value_comp();

The value_comp() function returns a function object that compares values.


C++ Stacks

The C++ Stack is a container adapter that gives the programmer the functionality of a stack -- specifically, a FILO (first-in, last-out) data structure.

Operators | compare and assign stacks
empty() | true if the stack is empty
pop() | removes the top element
push() | adds an element to the top
size() | returns the number of elements in the stack
top() | returns the top element of the stack


C++ Stacks

Operators

Syntax:
  ==
  <=
  >=
  <
  >
  !=

All of the above operators can be used on stacks. Equality is defined by stacks having the same elements in the same order.

empty

Syntax:
  bool empty();

The empty() function returns true if the current stack is empty, and false otherwise.

pop

Syntax:
  void pop();

The function pop() removes the top element of the current stack.

Related topics:
top(),

push

Syntax:
  void push( const TYPE &val );

The function push() adds val to the top of the current stack. For example:

    stack<int> s;
    for( int i=0; i < 10; i++ )
      s.push(i);

size

Syntax:
  size_type size();

The size() function returns the number of elements in the current stack. For example:

    stack<int> s;
    for( int i=0; i < 10; i++ )
      s.push(i);
    cout << "This stack has a size of " << s.size() << endl;

top

Syntax:
   TYPE &top();

The function top() returns a reference to the top element of the stack. For example, the following code displays and empties a stack.

    while( !s.empty() ) {
      cout << s.top() << " ";
      s.pop();
    }
Related topics:
pop(),


C++ Vectors

Vectors contain contiguous elements stored as an array. Accessing members of a vector or appending elements can be done in constant time, whereas locating a specific value or inserting elements into the vector takes linear time.

Constructors | methods to create vectors
Operators | assign and compare vectors
assign() | assign elements to the vector
at() | returns an element at a specific location
back() | returns the last element
begin() | returns an iterator to the first element
capacity() | the number of elements the vector can hold
clear() | removes all elements
empty() | true if the vector is empty
end() | returns an iterator to the last element
erase() | removes elements
front() | returns the first element
get_allocator() | returns the vector's allocator
insert() | insert elements into the vector
max_size() | returns the maximum number of elements that the vector can hold
pop_back() | removes the last element
push_back() | adds an element to the end of the vector
rbegin() | returns a reverse iterator to the end of the vector
rend() | returns a reverse iterator to the beginning of the vector
reserve() | sets the minimum capacity of the vector
resize() | change the size of the vector
size() | returns the size of the vector
swap() | exchange two vectors


C++ Vectors

Constructors

Syntax:
  vector();
  vector( size_type num, const TYPE &val );
  vector( const vector &from );
  vector( input_iterator start, input_iterator end );

C++ Vectors can be constructed with either:

  • Nothing - which creates an empty vector,
  • num and val - puts num copies of val in the vector,
  • from - creates a vector with the same contents as from, or
  • start and end - which creates a vector containing elements from start to end.
For example, the following example constructs a vector consisting of five copies of the integer 42.
vector<int> v1( 5, 42 );

Operators

Syntax:
  v1 == v2
  v1 != v2
  v1 <= v2
  v1 >= v2
  v1 < v2
  v1 > v2
  v[]

The C++ Vectors can be compared using the standard operators: ==, !=, <=, >=, <, and >. Individual elements of a vector can be examined with the [] operator.

Two vectors are equal if

  1. their size is the same, and
  2. each member in location i in one vector is equal to the the member in location i in the other vector.
Comparisons among vectors are done lexicographically.

Related topics:
at().

assign

Syntax:
  void assign( input_iterator start, input_iterator end );
  void assign( size_type num, const TYPE &val );

The assign() function either gives the current vector the values from start to end, or gives it num copies of val. This function will destroy the previous contents of the vector.

at

Syntax:
  TYPE at( size_type loc );

The at() function returns a reference to the element in the current vector at loc. The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the vector. For example, consider the following code:

vector<int> v( 5, 1 );
for( int i = 0; i < 10; i++ ) {
  cout << "Element " << i << " is " << v[i] << endl;
}

This code overrunns the end of the vector, producing potentially dangerous results. The following code would be much safer:

vector<int> v( 5, 1 );
for( int i = 0; i < 10; i++ ) {
  cout << "Element " << i << " is " << v.at(i) << endl;
}

Instead of attempting to read garbage values from memory, the at() function will realize that it is about to overrun the vector and will throw an exception.

Related topics:
The [] Operator

back

Syntax:
  TYPE back();

The back() function returns a reference to the last element in the current vector. For example:

vector<int> v;
for( int i = 0; i < 5; i++ ) {
  v.push_back(i);
}
cout << "The first element is " << v.front()
     << " and the last element is " << v.back() << endl;

This code produces the following output:

The first element is 0 and the last element is 4
Related topics:
front().

begin

Syntax:
  iterator begin();

The function begin() returns an iterator to the first element in the current vector. For example, the following code uses an iterator to display all of the elements in a vector:

vector<int> v1( 5, 789 );
vector<int>::iterator it;
for( it = v1.begin(); it != v1.end(); it++ )
  cout << *it << endl;
Related topics:
end().

capacity

Syntax:
  size_type capacity();

The capacity() function returns the number of elements that the current vector can hold before it will need to allocate more space.

clear

Syntax:
  void clear();

The function clear() deletes all of the elements in the current vector.

empty

Syntax:
  bool empty();

The empty() function returns true if the current vector has no elements, false otherwise. For example, the following code clears a given vector and displays its contents in reverse order:

vector<int> v;
for( int i = 0; i < 5; i++ ) {
  v.push_back(i);
}
while( !v.empty() ) {
  cout << v.back() << endl;
  v.pop_back();
}
Related topics:
size()

end

Syntax:
  iterator end();

The end() function returns an iterator just past the end of the current vector. Note that before you can access the last element of the vector, you'll have to decrement the iterator.

Related topics:
begin()

erase

Syntax:
  iterator erase( iterator loc );
  iterator erase( iterator start, iterator end );

The erase() function either deletes the element at location loc, or deletes the elements between start and end. The return value is the element after the last element erased. For example:

// Create a vector, load it with the first ten characters of the alphabet
vector<char> alphaVector;
for( int i=0; i < 10; i++ )
  alphaVector.push_back( i + 65 );
int size = alphaVector.size();
vector<char>::iterator startIterator;
vector<char>::iterator tempIterator;
for( int i=0; i < size; i++ ) {
  startIterator = alphaVector.begin();
  alphaVector.erase( startIterator );
  // Display the vector
  for( tempIterator = alphaVector.begin(); tempIterator != alphaVector.end(); tempIterator++ )
    cout << *tempIterator;
  cout << endl;
}

That code would display the following output:

BCDEFGHIJ
CDEFGHIJ
DEFGHIJ
EFGHIJ
FGHIJ
GHIJ
HIJ
IJ
J
Related topics:
pop_back().

front

Syntax:
  TYPE front();

The front() function returns a reference to the first element of the current vector.

Related topics:
back().

get_allocator

Syntax:
  allocator_type get_allocator();

The function get_allocator() returns the current vector's allocator.

insert

Syntax:
  iterator insert( iterator loc, const TYPE &val );
  void insert( iterator loc, size_type num, const TYPE &val );
  void insert( iterator loc, input_iterator start, input_iterator end );

The function insert() either:

  • inserts val before loc, returning an iterator to that element,
  • inserts num copies of val before loc, or
  • inserts the elements from start to end before loc.
For example:
// Create a vector, load it with the first 10 characters of the alphabet
vector<char> alphaVector;
for( int i=0; i < 10; i++ )
  alphaVector.push_back( i + 65 );
// Insert four C's into the vector
vector<char>::iterator theIterator = alphaVector.begin();
alphaVector.insert( theIterator, 4, 'C' );
// Display the vector
for( theIterator = alphaVector.begin(); theIterator != alphaVector.end(); theIterator++ )
  cout << *theIterator;

This code would display:

CCCCABCDEFGHIJ

max_size

Syntax:
  size_type max_size();

The max_size() function returns the maximum number of elements that the current vector can hold.

pop_back

Syntax:
  void pop_back();

The function pop_back() deletes the last element in the current vector. For example:

vector<char> alphaVector;
for( int i=0; i < 10; i++ )
  alphaVector.push_back( i + 65 );
int size = alphaVector.size();
vector<char>::iterator theIterator;
for( int i=0; i < size; i++ ) {
  alphaVector.pop_back();
  for( theIterator = alphaVector.begin(); theIterator != alphaVector.end(); theIterator++ )
    cout << *theIterator;
  cout << endl;
}

This code displays the following output:

ABCDEFGHI
ABCDEFGH
ABCDEFG
ABCDEF
ABCDE
ABCD
ABC
AB
A
Related topics:
erase().

push_back

Syntax:
  void push_back( const TYPE &val );

The push_back() function appends val to the end of the current vector.

rbegin

Syntax:
  reverse_iterator rbegin();

The rbegin() function returns a reverse iterator to the end of the current vector.

rend

Syntax:
  reverse_iterator rend();

The function rend() returns a reverse iterator to the beginning of the current vector.

reserve

Syntax:
  void reserve( size_type size );

The reserve() function sets the capacity of the current vector to at least size.

resize

Syntax:
  void resize( size_type size, TYPE val );

The function resize() changes the size of the current vector to size, setting any newly-created elements to val.

size

Syntax:
  size_type size();

The size() function returns the number of elements in the current vector.

Related topics:
empty()

swap

Syntax:
  void swap( vector &from );

The swap() function exchanges the elements of the current vector with those of from.


C++ Iterators

Iterators are used to access members of the container classes, and can be used in a similar manner to pointers. For example, one might use an iterator to step through the elements of a vector. There are several different types of iterators:

Iterator | Description
input_iterator | Read values with forward movement. These can be incremented, compared, and dereferenced.
output_iterator | Write values with forward movement. These can be incremented and dereferenced.
forward_iterator | Read or write values with forward movement. These combine the functionality of input and output iterators with the ability to store the iterators value.
bidirectional_iterator | Read and write values with forward and backward movement. These are like the forward iterators, but you can increment and decrement them.
random_iterator | Read and write values with random access. These are the most powerful iterators, combining the functionality of bidirectional iterators with the ability to do pointer arithmetic and pointer comparisons.
reverse_iterator | Either a random iterator or a bidirectional iterator that moves in reverse direction.

Each of the container classes is associated with a type of iterator, and each of the STL algorithms uses a certain type of iterator. For example, vectors are associated with random-access iterators, which means that they can use algorithms that require random access. Since random-access iterators encompass all of the characteristics of the other iterators, vectors can use algorithms designed for other iterators as well.

The following code creates and uses an iterator with a vector:

  vector<int> the_vector;
  vector<int>::iterator the_iterator;
  for( int i=0; i < 10; i++ )
    the_vector.push_back(i);
  int total = 0;
  the_iterator = the_vector.begin();
  while( the_iterator != the_vector.end() ) {
    total += *the_iterator;
    the_iterator++;
  }
  cout << "Total=" << total << endl;
Notice that you can access the elements of the container by dereferencing the iterator.


All C Functions

  • abort
  • abs
  • acos
  • asctime
  • asin
  • assert
  • atan
  • atan2
  • atexit
  • atof
  • atoi
  • atol
  • bsearch
  • calloc
  • ceil
  • clearerr
  • clock
  • cos
  • cosh
  • ctime
  • difftime
  • div
  • exit
  • exp
  • fabs
  • fclose
  • feof
  • ferror
  • fflush
  • fgetc
  • fgetpos
  • fgets
  • floor
  • fmod
  • fopen
  • fprintf
  • fputc
  • fputs
  • fread
  • free
  • freopen
  • frexp
  • fscanf
  • fseek
  • fsetpos
  • ftell
  • fwrite
  • getc
  • getchar
  • getenv
  • gets
  • gmtime
  • isalnum
  • isalpha
  • iscntrl
  • isdigit
  • isgraph
  • islower
  • isprint
  • ispunct
  • isspace
  • isupper
  • isxdigit
  • labs
  • ldexp
  • ldiv
  • localtime
  • log
  • log10
  • longjmp
  • malloc
  • memchr
  • memcmp
  • memcpy
  • memmove
  • memset
  • mktime
  • modf
  • perror
  • pow
  • printf
  • putc
  • putchar
  • puts
  • qsort
  • raise
  • rand
  • realloc
  • remove
  • rename
  • rewind
  • scanf
  • setbuf
  • setjmp
  • setvbuf
  • signal
  • sin
  • sinh
  • sprintf
  • sqrt
  • srand
  • sscanf
  • strcat
  • strchr
  • strcmp
  • strcoll
  • strcpy
  • strcspn
  • strerror
  • strftime
  • strlen
  • strncat
  • strncmp
  • strncpy
  • strpbrk
  • strrchr
  • strspn
  • strstr
  • strtod
  • strtok
  • strtol
  • strtoul
  • strxfrm
  • system
  • tan
  • tanh
  • time
  • tmpfile
  • tmpnam
  • tolower
  • toupper
  • ungetc
  • va_arg
  • vprintf, vfprintf, & vsprintf


All C++ Functions

  • Constructors (deque)
  • Constructors (bitset)
  • Constructors (string)
  • Constructors (vector)
  • Operators (deque)
  • Operators (stack)
  • Operators (string)
  • Operators (vector)
  • any (bitset)
  • append (string)
  • assign (deque)
  • assign (list)
  • assign (string)
  • assign (vector)
  • at (deque)
  • at (string)
  • at (vector)
  • back (deque)
  • back (list)
  • back (queue)
  • back (vector)
  • bad (io)
  • begin (deque)
  • begin (list)
  • begin (map)
  • begin (multimap)
  • begin (multiset)
  • begin (set)
  • begin (string)
  • begin (vector)
  • c_str (string)
  • capacity (string)
  • capacity (vector)
  • clear (deque)
  • clear (io)
  • clear (list)
  • clear (map)
  • clear (multimap)
  • clear (multiset)
  • clear (set)
  • clear (vector)
  • compare (string)
  • copy (string)
  • count (bitset)
  • count (map)
  • count (multimap)
  • count (multiset)
  • count (set)
  • data (string)
  • empty (deque)
  • empty (list)
  • empty (map)
  • empty (multimap)
  • empty (multiset)
  • empty (priorityqueue)
  • empty (queue)
  • empty (set)
  • empty (stack)
  • empty (string)
  • empty (vector)
  • end (deque)
  • end (list)
  • end (map)
  • end (multimap)
  • end (multiset)
  • end (set)
  • end (string)
  • end (vector)
  • eof (io)
  • equal_range (map)
  • equal_range (multimap)
  • equal_range (multiset)
  • equal_range (set)
  • erase (deque)
  • erase (list)
  • erase (map)
  • erase (multimap)
  • erase (multiset)
  • erase (set)
  • erase (string)
  • erase (vector)
  • fail (io)
  • fill (io)
  • find (map)
  • find (multimap)
  • find (multiset)
  • find (set)
  • find (string)
  • find_first_not_of (string)
  • find_first_of (string)
  • find_last_not_of (string)
  • find_last_of (string)
  • flags (io)
  • flip (bitset)
  • flush (io)
  • front (deque)
  • front (list)
  • front (queue)
  • front (vector)
  • fstream (io)
  • gcount (io)
  • get (io)
  • get_allocator (deque)
  • get_allocator (list)
  • get_allocator (map)
  • get_allocator (multimap)
  • get_allocator (multiset)
  • get_allocator (set)
  • get_allocator (string)
  • get_allocator (vector)
  • getline (io)
  • good (io)
  • ignore (io)
  • insert (deque)
  • insert (list)
  • insert (map)
  • insert (multimap)
  • insert (multiset)
  • insert (set)
  • insert (string)
  • insert (vector)
  • key_comp (map)
  • key_comp (multimap)
  • key_comp (multiset)
  • key_comp (set)
  • length (string)
  • lower_bound (map)
  • lower_bound (multimap)
  • lower_bound (multiset)
  • lower_bound (set)
  • max_size (deque)
  • max_size (list)
  • max_size (map)
  • max_size (multimap)
  • max_size (multiset)
  • max_size (set)
  • max_size (string)
  • max_size (vector)
  • merge (list)
  • none (bitset)
  • open (io)
  • peek (io)
  • pop (priorityqueue)
  • pop (queue)
  • pop (stack)
  • pop_back (deque)
  • pop_back (list)
  • pop_back (vector)
  • pop_front (deque)
  • pop_front (list)
  • precision (io)
  • push (priorityqueue)
  • push (queue)
  • push (stack)
  • push_back (deque)
  • push_back (list)
  • push_back (vector)
  • push_front (deque)
  • push_front (list)
  • put (io)
  • putback (io)
  • rbegin (deque)
  • rbegin (list)
  • rbegin (map)
  • rbegin (multimap)
  • rbegin (multiset)
  • rbegin (set)
  • rbegin (string)
  • rbegin (vector)
  • rdstate (io)
  • read (io)
  • remove (list)
  • remove_if (list)
  • rend (deque)
  • rend (list)
  • rend (map)
  • rend (multimap)
  • rend (multiset)
  • rend (set)
  • rend (string)
  • rend (vector)
  • replace (string)
  • reserve (string)
  • reserve (vector)
  • reset (bitset)
  • resize (deque)
  • resize (list)
  • resize (string)
  • resize (vector)
  • reverse (list)
  • rfind (string)
  • seekg (io)
  • seekp (io)
  • set (bitset)
  • setf (io)
  • size (bitset)
  • size (deque)
  • size (list)
  • size (map)
  • size (multimap)
  • size (multiset)
  • size (priorityqueue)
  • size (queue)
  • size (set)
  • size (stack)
  • size (string)
  • size (vector)
  • sort (list)
  • splice (list)
  • substr (string)
  • swap (deque)
  • swap (list)
  • swap (map)
  • swap (multimap)
  • swap (multiset)
  • swap (set)
  • swap (string)
  • swap (vector)
  • sync_with_stdio (io)
  • tellg (io)
  • tellp (io)
  • test (bitset)
  • to_string (bitset)
  • to_ulong (bitset)
  • top (priorityqueue)
  • top (stack)
  • unique (list)
  • unsetf (io)
  • upper_bound (map)
  • upper_bound (multimap)
  • upper_bound (multiset)
  • upper_bound (set)
  • value_comp (map)
  • value_comp (multimap)
  • value_comp (multiset)
  • value_comp (set)
  • width (io)
  • write (io)


Questions?

cppreference.com -> FAQ

Frequently Asked Questions

Who is this site meant for?

There are no "Introduction to Programming" tutorials here. This site is meant to be used by more-or-less experienced C++ programmers, who have a good idea of what they want to do and simply need to look up the syntax. If you're interested in learning C/C++, try one of these sites:
  • How C Programming Works
  • C Programming
  • C++ Language Tutorial

Does this site contain a complete and definitive list of C/C++ functions?

Few things in life are absolute. If you don't find what you are looking for here, don't assume that it doesn't exist. Do a search on Google for it.

Is there an archived version of this site available?

You can download an archived version of cppreference.com here. If you're interested in getting archived versions of websites in general, you might want to check out utilities like GNU's wget (Windows version here).

Some of the examples on this site don't work on my system. What's going on?

Most of the code on this site was compiled under Linux (Red Hat or Debian) with the GNU Compiler Collection. Since this site is merely a reference for the Standard C and C++ specification, (check here, too) not every compiler will support every function listed here. For example,
  • Header files change like mad. To include the necessary support for C++ Vectors, you might have to use any of these:
    #include <vector>
#include <Vector>
#include <vector.h>
    (according to the spec, the first of those should work, and the compiler should know enough to use it to reference the real vector header file.)
  • Another header file issue is that newer compilers can use a more platform-independent commands to include standard C libraries. For example, you might be able to use
    #include <cstdio>
    instead of
    #include <stdio.h>
  • All of the code on this site assumes that the correct namespace has been designated. If your compiler is a little old, then you might be able to get away with using simple statements like:
          cout << "hello world!";
    However, newer compilers require that you either use
          std::cout << "hello world!";
    or declare what namespace to use with the "using namespace" command.
  • Certain popular compilers (like the one shipped with Microsoft's Visual C++) have alternative or additions to the C++ Standard Template Library. For example, the MFC in Visual C++ provides you with the string type "CString", which has string functionality but is not part of the C++ STL.
...The list goes on and on. In other words, individual results may vary.

You've got an error in this site.

If you find any errors in this reference, please feel free to contact us -- feedback and code examples are always welcome.

What's up with this site?

Think of it as a community service, for geeks.


People who helped out

cppreference.com -> Credits

Huge thanks to all these people for sending in bug fixes and suggestions on how to improve the site:

Adrian Pfisterer - Alex Vinokur - Alexandre Kostine - Andre - Andrew L Roth - Brian Higgins - Carl - Cedric Blaser - Chris H - Chris Yate - Christoph Vogelbusch - Daniel Lorch - Darsh Ranjan - Dave Schuyler - Dave T - Deepak Goyal - Dzu Nguyen - Gerhard Grossauer - Henrik Huttunen - JP (Pete) Donnell - Jari Karppinen - Jeff Bowden - Jeroen Missinne - Jonathan Kleid - Joseph Bruni - Justin M. Lee - Katherine Haines - Kuang-che Wu - Leor Zolman - Lucas Fisher - Mael Herz - Magnus Kulke - Manish Malik - Martin - Martijn van de Giessen - Mike Jennings - Nick Gianakas - Nicolas Boichat - Olivier Ricou - Onur Tugcu - Osku Salerma - Paul L. Tomlinson - Philip Dunstan - Phillip Lee - Roger D Pack - Salman Mahbub - Shibukawa Yoshiki - Stefan Suffa - Thomas Volk - Tom (prkchp) - Wouter Lievens - XenteX

Thank you!

downloaded from www.cppreference.com and compiled to .chm by cz.filda


Page not retrieved! - HTTrack Website Copier

%s
HTTrack Website Copier - Open Source offline browser

Oops!...

This page has not been retrieved by HTTrack Website Copier.

Mirror by HTTrack Website Copier
© 2002 Xavier Roche & other contributors - Web Design: Kauler Leto.


Complexity

There are different measurements of the speed of any given algorithm. Given an input size of N, they can be described as follows:

Name | Speed | Description
exponential time | slow | takes an amount of time proportional to a constant raised to the Nth power (K^N)
polynomial time | fast | takes an amount of time proportional to N raised to some constant power (N^K)
linear time | faster | takes an amount of time directly proportional to N (K * N)
logarithmic time | much faster | takes an amount of time proportional to the logarithm of N (log(N))
constant time | fastest | takes a fixed amount of time, no matter how large the input is (K)


C++ Containers

The C++ Containers (vectors, lists, etc.) are generic vessels capable of holding many different types of data. For example, the following statement creates a vector of integers:
vector<int> v;
Containers can hold standard objects (like the int in the above example) as well as custom objects, as long as the objects in the container meet a few requirements:
  • The object must have a default constructor,
  • an accessible destructor, and
  • an accessible assignment operator.
When describing the functions associated with these various containers, this website defines the word TYPE to be the object type that the container holds. For example, in the above statement, TYPE would be int.


Links

Here are some links to other language references:

  • C++ (Dinkumware)
  • C++ Language and Library
  • Java 1.4 (Sun)
  • MySQL
  • Perl
  • Python
  • Visual C++ STL (Microsoft)


Static Returns!

cppreference.com -> Static Return

Watch out.

This function returns a variable that is statically located, and therefore overwritten each time this function is called. If you want to save the return value of this function, you should manually save it elsewhere.
Of course, when you save it elsewhere, you should make sure to actually copy the value(s) of this variable to another location. If the return value is a struct, you should make a new struct, then copy over the members of the struct.