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.

Display all entries for C++ Bitsets on one page, or view entries individually:

Bitset Constructors | create new bitsets
Bitset Operators | compare and assign bitsets
any | true if any bits are set
count | returns the number of set bits
flip | reverses the bitset
none | true if no bits are set
reset | sets bits to zero
set | sets bits
size | number of bits that the bitset can hold
test | returns the value of a given bit
to_string | string representation of the bitset
to_ulong | returns an integer representation of the bitset


C++ Bitsets::Bitset Constructors

Bitset 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;


C++ Bitsets::Bitset Operators

Bitset 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


C++ Bitsets::any

any
Syntax:
  bool any();

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

Related topics:


C++ Bitsets::count

count
Syntax:
  size_type count();

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

Related topics:
any


C++ Bitsets::flip

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.


C++ Bitsets::none

none
Syntax:
  bool none();

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

Related topics:
any


C++ Bitsets::reset

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.


C++ Bitsets::set

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.


C++ Bitsets::size

size
Syntax:
  size_t size();

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


C++ Bitsets::test

test
Syntax:
  bool test( size_t pos );

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


C++ Bitsets::to_string

to_string
Syntax:
  string to_string();

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

Related topics:
to_ulong


C++ Bitsets::to_ulong

to_ulong
Syntax:
  unsigned long to_ulong();

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

Related topics:
to_string


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.

Display all entries for C++ Double-ended Queues on one page, or view entries individually:

Container constructors | create dequeues and initialize them with some data
Container operators | compare, assign, and access elements of a dequeue
assign | assign elements to a dequeue
at | returns an element at a specific location
back | returns a reference to last element of a dequeue
begin | returns an iterator to the beginning of the dequeue
clear | removes all elements from the dequeue
empty | true if the dequeue has no elements
end | returns an iterator just past the last element of a dequeue
erase | removes elements from a dequeue
front | returns a reference to the first element of a dequeue
insert | inserts elements into the dequeue
max_size | returns the maximum number of elements that the dequeue can hold
pop_back | removes the last element of a dequeue
pop_front | removes the first element of the dequeue
push_back | add an element to the end of the dequeue
push_front | add an element to the front of the dequeue
rbegin | returns a reverse_iterator to the end of the dequeue
rend | returns a reverse_iterator to the beginning of the dequeue
resize | change the size of the dequeue
size | returns the number of items in the dequeue
swap | swap the contents of this dequeue with another


C++ Double-ended Queues::Container constructors

Container constructors
Syntax:
  container();
  container( const container& c );
  container( size_type num, const TYPE& val = TYPE() );
  container( input_iterator start, input_iterator end );
  ~container();

The default dequeue constructor takes no arguments, creates a new instance of that dequeue.

The second constructor is a default copy constructor that can be used to create a new dequeue that is a copy of the given dequeue c.

The third constructor creates a dequeue with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a vector consisting of five copies of the integer 42:

 vector<int> v1( 5, 42 );

The last constructor creates a dequeue that is initialized to contain the elements between start and end. For example:

 // create a vector of random integers
 cout << "original vector: ";
 vector<int> v;
 for( int i = 0; i < 10; i++ ) {
   int num = (int) rand() % 10;
   cout << num << " ";
   v.push_back( num );
 }
 cout << endl;
 // find the first element of v that is even
 vector<int>::iterator iter1 = v.begin();
 while( iter1 != v.end() && *iter1 % 2 != 0 ) {
   iter1++;
 }
 // find the last element of v that is even
 vector<int>::iterator iter2 = v.end();
 do {
   iter2--;
 } while( iter2 != v.begin() && *iter2 % 2 != 0 );
 cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;
 cout << "new vector: ";
 vector<int> v2( iter1, iter2 );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, this code displays the following output:

 original vector: 1 9 7 9 2 7 2 1 9 8
 first even number: 2, last even number: 8
 new vector: 2 7 2 1 9

All of these constructors run in linear time except the first, which runs in constant time.

The default destructor is called when the dequeue should be destroyed.


C++ Double-ended Queues::Container operators

Container operators
Syntax:
  TYPE& operator[]( size_type index );
  const TYPE& operator[]( size_type index ) const;
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Individual elements of a dequeue can be examined with the [] operator.

Performing a comparison or assigning one dequeue to another takes linear time. The [] operator runs in constant time.

Two `containers` are equal if:

  1. Their size is the same, and
  2. Each member in location i in one dequeue is equal to the the member in location i in the other dequeue.

Comparisons among dequeues are done lexicographically.

For example, the following code uses the [] operator to access all of the elements of a vector:

 vector<int> v( 5, 1 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << "Element " << i << " is " << v[i] << endl;
 }

Related topics:
at


C++ Double-ended Queues::assign

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

The assign() function either gives the current dequeue the values from start to end, or gives it num copies of val.

This function will destroy the previous contents of the dequeue.

For example, the following code uses assign() to put 10 copies of the integer 42 into a vector:

 vector<int> v;
 v.assign( 10, 42 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << v[i] << " ";
 }
 cout << endl;

The above code displays the following output:

 42 42 42 42 42 42 42 42 42 42

The next example shows how assign() can be used to copy one vector to another:

 vector<int> v1;
 for( int i = 0; i < 10; i++ ) {
   v1.push_back( i );
 }
 vector<int> v2;
 v2.assign( v1.begin(), v1.end() );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, the above code displays the following output:

 0 1 2 3 4 5 6 7 8 9

Related topics:
(C++ Strings) assign
insert
push_back
push_front


C++ Double-ended Queues::at

at
Syntax:
  TYPE& at( size_type loc );
  const TYPE& at( size_type loc ) const;

The at() function returns a reference to the element in the dequeue at index loc. The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the dequeue.

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:
(C++ Multimaps) Container operators
Container operators


C++ Double-ended Queues::back

back
Syntax:
  TYPE& back();
  const TYPE& back() const;

The back() function returns a reference to the last element in the dequeue.

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

The back() function runs in constant time.


C++ Double-ended Queues::begin

begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the dequeue. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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;
   }


C++ Double-ended Queues::clear

clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the dequeue. clear() runs in linear time.

Related topics:
erase


C++ Double-ended Queues::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the dequeue has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a dequeue and display 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


C++ Double-ended Queues::end

end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the dequeue.

Note that before you can access the last element of the dequeue using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.


C++ Double-ended Queues::erase

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.

The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, dequeues, and strings. The multiple-element version of erase always takes linear time.

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

In the next example, erase() is called with two iterators to delete a range of elements from a vector:

 // 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 );
 }
 // display the complete vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;
 // use erase to remove all but the first two and last three elements
 // of the vector
 alphaVector.erase( alphaVector.begin()+2, alphaVector.end()-3 );
 // display the modified vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;

When run, the above code displays:

 ABCDEFGHIJ
 ABHIJ

Related topics:
clear
insert
pop_back
pop_front
(C++ Lists) remove
(C++ Lists) remove_if


C++ Double-ended Queues::front

front
Syntax:
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the dequeue, and runs in constant time.


C++ Double-ended Queues::insert

insert
Syntax:
  iterator insert( iterator loc, const TYPE& val );
  void insert( iterator loc, size_type num, const TYPE& val );
  template<TYPE> void insert( iterator loc, input_iterator start, input_iterator end );

The insert() function either:

  • inserts val before loc, returning an iterator to the element inserted,
  • 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

Related topics:
assign
erase
(C++ Lists) merge
push_back
push_front
(C++ Lists) splice


C++ Double-ended Queues::max_size

max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size


C++ Double-ended Queues::pop_back

pop_back
Syntax:
  void pop_back();

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

pop_back() runs in constant time.


C++ Double-ended Queues::pop_front

pop_front
Syntax:
  void pop_front();

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

The pop_front() function runs in constant time.


C++ Double-ended Queues::push_back

push_back
Syntax:
  void push_back( const TYPE& val );

The push_back() function appends val to the end of the dequeue.

For example, the following code puts 10 integers into a list:

   list<int> the_list;
   for( int i = 0; i < 10; i++ )
     the_list.push_back( i );

When displayed, the resulting list would look like this:

 0 1 2 3 4 5 6 7 8 9

push_back() runs in constant time.


C++ Double-ended Queues::push_front

push_front
Syntax:
  void push_front( const TYPE& val );

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

push_front() runs in constant time.


C++ Double-ended Queues::rbegin

rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current dequeue.

rbegin() runs in constant time.


C++ Double-ended Queues::rend

rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current dequeue.

rend() runs in constant time.


C++ Double-ended Queues::resize

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

The function resize() changes the size of the dequeue to size. If val is specified then any newly-created elements will be initialized to have a value of val.

This function runs in linear time.

Related topics:
(C++ Multimaps) Container constructors & destructors
(C++ Strings) capacity
size


C++ Double-ended Queues::size

size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
resize


C++ Double-ended Queues::swap

swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current dequeue with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice


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 io stream format flags.

Display all entries for C++ I/O on one page, or view entries individually:

I/O 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 | access or manipulate io stream format 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 the precision of a stream
put | write characters
putback | return characters to a stream
rdstate | returns the state flags of the stream
read | read data into a buffer
seekg | perform random access on an input stream
seekp | perform random access on output streams
setf | set format flags
sync_with_stdio | synchronize with standard I/O
tellg | read input stream pointers
tellp | read output stream pointers
unsetf | clear io stream format flags
width | access and manipulate the minimum field width
write | write characters


C++ I/O::I/O Constructors

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.


C++ I/O::bad

bad
Syntax:
  bool bad();

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


C++ I/O::clear

clear
Syntax:
  void clear( iostate flags = ios::goodbit );

The function clear() clears the io stream state flags associated with the current stream. The flags argument defaults to ios::goodbit, which means that all flags will be cleared. Otherwise, only the flags specified by flags are cleared.


C++ I/O::close

close
Syntax:
  void close();

The close() function closes the associated file stream.


C++ I/O::eof

eof
Syntax:
  bool eof();

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

For example, the following code reads data from an input stream in and writes it to an output stream out, using eof() at the end to check if an error occurred:

 char buf[BUFSIZE];
 do {
   in.read( buf, BUFSIZE );
   std::streamsize n = in.gcount();
   out.write( buf, n );
 } while( in.good() );
 if( in.bad() || !in.eof() ) {
   // fatal error occurred
 }
 in.close();


C++ I/O::fail

fail
Syntax:
  bool fail();

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


C++ I/O::fill

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.


C++ I/O::flags

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

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


C++ I/O::flush

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.


C++ I/O::gcount

gcount
Syntax:
  streamsize gcount();

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


C++ I/O::get

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 a file called temp.txt, character by character:

   char ch;
   ifstream fin( "temp.txt" );
   while( fin.get(ch) )
     cout << ch;
   fin.close();

Related topics:
gcount
getline
(C++ Strings) getline
ignore
peek
put
read


C++ I/O::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.

Those using a Microsoft compiler may find that getline() reads an extra character, and should consult the documentation on the Microsoft getline bug.

Related topics:
gcount
get
(C++ Strings) getline
ignore
read


C++ I/O::good

good
Syntax:
  bool good();

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


C++ I/O::ignore

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 (where num defaults to 1) or until the character delim is read (where delim defaults to EOF).


C++ I/O::open

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

The function open() is used with file streams. It opens filename and associates it with the current stream. The optional io stream mode flag mode defaults to ios::in for ifstream, ios::out for ofstream, and ios::in|ios::out for fstream.

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;
 }


C++ I/O::peek

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.


C++ I/O::precision

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 sets the precision of the cout stream to 5:

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

This code displays the following output:

   314.16


C++ I/O::put

put
Syntax:
  ostream &put( char ch );

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


C++ I/O::putback

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
(Standard C I/O) ungetc


C++ I/O::rdstate

rdstate
Syntax:
  iostate rdstate();

The rdstate() function returns the io stream state flags of the current stream.


C++ I/O::read

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 );
   }


C++ I/O::seekg

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.


C++ I/O::seekp

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().


C++ I/O::setf

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

The function setf() sets the io stream format flags of the current stream to flags. The optional needed argument specifies that only the flags that are in both flags and needed should be set. The return value is the previous configuration of io stream format 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 io stream manipulators.


C++ I/O::sync_with_stdio

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.


C++ I/O::tellg

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.


C++ I/O::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();


C++ I/O::unsetf

unsetf
Syntax:
  void unsetf( fmtflags flags );

The function unsetf() uses flags to clear the io stream format flags associated with the current stream.


C++ I/O::width

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

The function width() returns the current width, which is defined as the minimum number of characters to display with each output. The optional argument w can be used to set the width.

For example:

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

displays

       2

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


C++ I/O::write

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.


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.

Display all entries for C++ Lists on one page, or view entries individually:

Container constructors | create lists and initialize them with some data
Container operators | assign and compare lists
assign | assign elements to a list
back | returns a reference to last element of a list
begin | returns an iterator to the beginning of the list
clear | removes all elements from the list
empty | true if the list has no elements
end | returns an iterator just past the last element of a list
erase | removes elements from a list
front | returns a reference to the first element of a list
insert | inserts elements into the list
max_size | returns the maximum number of elements that the list can hold
merge | merge two lists
pop_back | removes the last element of a list
pop_front | removes the first element of the list
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 end of the list
remove | removes elements from a list
remove_if | removes elements conditionally
rend | returns a reverse_iterator to the beginning of the list
resize | change the size of the list
reverse | reverse the list
size | returns the number of items in the list
sort | sorts the list
splice | merge two lists in constant time
swap | swap the contents of this list with another
unique | removes duplicate elements


C++ Lists::Container constructors

Container constructors
Syntax:
  container();
  container( const container& c );
  container( size_type num, const TYPE& val = TYPE() );
  container( input_iterator start, input_iterator end );
  ~container();

The default list constructor takes no arguments, creates a new instance of that list.

The second constructor is a default copy constructor that can be used to create a new list that is a copy of the given list c.

The third constructor creates a list with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a vector consisting of five copies of the integer 42:

 vector<int> v1( 5, 42 );

The last constructor creates a list that is initialized to contain the elements between start and end. For example:

 // create a vector of random integers
 cout << "original vector: ";
 vector<int> v;
 for( int i = 0; i < 10; i++ ) {
   int num = (int) rand() % 10;
   cout << num << " ";
   v.push_back( num );
 }
 cout << endl;
 // find the first element of v that is even
 vector<int>::iterator iter1 = v.begin();
 while( iter1 != v.end() && *iter1 % 2 != 0 ) {
   iter1++;
 }
 // find the last element of v that is even
 vector<int>::iterator iter2 = v.end();
 do {
   iter2--;
 } while( iter2 != v.begin() && *iter2 % 2 != 0 );
 cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;
 cout << "new vector: ";
 vector<int> v2( iter1, iter2 );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, this code displays the following output:

 original vector: 1 9 7 9 2 7 2 1 9 8
 first even number: 2, last even number: 8
 new vector: 2 7 2 1 9

All of these constructors run in linear time except the first, which runs in constant time.

The default destructor is called when the list should be destroyed.


C++ Lists::Container operators

Container operators
Syntax:
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one list to another takes linear time.

Two lists are equal if:

  1. Their size is the same, and
  2. Each member in location i in one list is equal to the the member in location i in the other list.

Comparisons among lists are done lexicographically.

Related topics:
(C++ Strings) String operators
(C++ Strings) at
merge
unique


C++ Lists::assign

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

The assign() function either gives the current list the values from start to end, or gives it num copies of val.

This function will destroy the previous contents of the list.

For example, the following code uses assign() to put 10 copies of the integer 42 into a vector:

 vector<int> v;
 v.assign( 10, 42 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << v[i] << " ";
 }
 cout << endl;

The above code displays the following output:

 42 42 42 42 42 42 42 42 42 42

The next example shows how assign() can be used to copy one vector to another:

 vector<int> v1;
 for( int i = 0; i < 10; i++ ) {
   v1.push_back( i );
 }
 vector<int> v2;
 v2.assign( v1.begin(), v1.end() );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, the above code displays the following output:

 0 1 2 3 4 5 6 7 8 9

Related topics:
(C++ Strings) assign
insert
push_back
push_front


C++ Lists::back

back
Syntax:
  TYPE& back();
  const TYPE& back() const;

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

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

The back() function runs in constant time.


C++ Lists::begin

begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the list. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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;
   }


C++ Lists::clear

clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the list. clear() runs in linear time.

Related topics:
erase


C++ Lists::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the list has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a list and display 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


C++ Lists::end

end
Syntax:
  iterator end();
  const_iterator end() const;

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

Note that before you can access the last element of the list using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.


C++ Lists::erase

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.

The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, dequeues, and strings. The multiple-element version of erase always takes linear time.

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

In the next example, erase() is called with two iterators to delete a range of elements from a vector:

 // 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 );
 }
 // display the complete vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;
 // use erase to remove all but the first two and last three elements
 // of the vector
 alphaVector.erase( alphaVector.begin()+2, alphaVector.end()-3 );
 // display the modified vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;

When run, the above code displays:

 ABCDEFGHIJ
 ABHIJ


C++ Lists::front

front
Syntax:
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the list, and runs in constant time.


C++ Lists::insert

insert
Syntax:
  iterator insert( iterator loc, const TYPE& val );
  void insert( iterator loc, size_type num, const TYPE& val );
  template<TYPE> void insert( iterator loc, input_iterator start, input_iterator end );

The insert() function either:

  • inserts val before loc, returning an iterator to the element inserted,
  • 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


C++ Lists::max_size

max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size


C++ Lists::merge

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

The function merge() merges the list with lst, producing a combined list that is ordered with respect to the < operator. If compfunction is specified, then it is used as the comparison function for the lists instead of <.

merge() runs in linear time.


C++ Lists::pop_back

pop_back
Syntax:
  void pop_back();

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

pop_back() runs in constant time.


C++ Lists::pop_front

pop_front
Syntax:
  void pop_front();

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

The pop_front() function runs in constant time.


C++ Lists::push_back

push_back
Syntax:
  void push_back( const TYPE& val );

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

For example, the following code puts 10 integers into a list:

   list<int> the_list;
   for( int i = 0; i < 10; i++ )
     the_list.push_back( i );

When displayed, the resulting list would look like this:

 0 1 2 3 4 5 6 7 8 9

push_back() runs in constant time.


C++ Lists::push_front

push_front
Syntax:
  void push_front( const TYPE& val );

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

push_front() runs in constant time.


C++ Lists::rbegin

rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current list.

rbegin() runs in constant time.


C++ Lists::remove

remove
Syntax:
  void remove( const TYPE &val );

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

For example, the following code creates a list of the first 10 characters of the alphabet, then uses remove() to remove the letter 'E' from the list:

   // 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 runs in linear time.


C++ Lists::remove_if

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.

remove_if() runs in linear time.


C++ Lists::rend

rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current list.

rend() runs in constant time.


C++ Lists::resize

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

The function resize() changes the size of the list to size. If val is specified then any newly-created elements will be initialized to have a value of val.

This function runs in linear time.

Related topics:
(C++ Multimaps) Container constructors & destructors
(C++ Strings) capacity
size


C++ Lists::reverse

reverse
Syntax:
  void reverse();

The function reverse() reverses the list, and takes linear time.

Related topics:
sort


C++ Lists::size

size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
resize


C++ Lists::sort

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

The sort() function is used to sort lists. Ordering is done via the < operator, unless compfunction is specified, in which case it is used to determine if an element is less than another.

Sorting takes n * log(n) time.

Related topics:
reverse


C++ Lists::splice

splice
Syntax:
  void splice( iterator pos, list& lst );
  void splice( iterator pos, list& lst, iterator del );
  void splice( iterator pos, list& 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.

splice() simply moves elements from one list to another, and doesn't actually do any copying or deleting. Because of this, splice() runs in constant time.


C++ Lists::swap

swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current list with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
splice


C++ Lists::unique

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

The function unique() removes all duplicate elements from the list. Equality is tested using the == operator, unless pr is specified as a replacement. The ordering of the elements in a list should not change after a call to unique().

unique() runs in linear time.


C++ Maps

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

Display all entries for C++ Maps on one page, or view entries individually:

Container constructors & destructors | default methods to allocate, copy, and deallocate maps
Map operators | assign, compare, and access elements of a map
begin | returns an iterator to the beginning of the map
clear | removes all elements from the map
count | returns the number of elements matching a certain key
empty | true if the map has no elements
end | returns an iterator just past the last element of a map
equal_range | returns iterators to the first and just past the last elements matching a specific key
erase | removes elements from a map
find | returns an iterator to specific elements
insert | insert items into a map
key_comp | returns the function that compares keys
lower_bound | returns an iterator to the first element greater than or equal to a certian value
max_size | returns the maximum number of elements that the map can hold
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 items in the map
swap | swap the contents of this map with another
upper_bound | returns an iterator to the first element greater than a certain value
value_comp | returns the function that compares values


C++ Maps::Container constructors & destructors

Container constructors & destructors
Syntax:
  container();
  container( const container& c );
  ~container();

Every map has a default constructor, copy constructor, and destructor.

The default constructor takes no arguments, creates a new instance of that map, and runs in constant time. The default copy constructor runs in linear time and can be used to create a new map that is a copy of the given map c.

The default destructor is called when the map should be destroyed.

For example, the following code creates a pointer to a vector of integers and then uses the default map constructor to allocate a memory for a new vector:

 vector<int>* v;
 v = new vector<int>();

Related topics:
(C++ Strings) resize


C++ Maps::Map operators

Map operators
Syntax:
  TYPE& operator[]( const key_type& key );
  map operator=(const map& c2);
  bool operator==(const map& c1, const map& c2);
  bool operator!=(const map& c1, const map& c2);
  bool operator<(const map& c1, const map& c2);
  bool operator>(const map& c1, const map& c2);
  bool operator<=(const map& c1, const map& c2);
  bool operator>=(const map& c1, const map& c2);

Maps can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Individual elements of a map can be examined with the [] operator.

Performing a comparison or assigning one map to another takes linear time.

Two maps are equal if:

  1. Their size is the same, and
  2. Each member in location i in one map is equal to the the member in location i in the other map.

Comparisons among maps are done lexicographically.

Related topics:
insert


C++ Maps::begin

begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the map. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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;
   }


C++ Maps::clear

clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the map. clear() runs in linear time.

Related topics:
(C++ Lists) erase


C++ Maps::count

count
Syntax:
  size_type count( const key_type& key );

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

count() should run in logarithmic time.


C++ Maps::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the map has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a map and display 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


C++ Maps::end

end
Syntax:
  iterator end();
  const_iterator end() const;

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

Note that before you can access the last element of the map using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.


C++ Maps::equal_range

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 a point just after the last element that contains key.


C++ Maps::erase

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.


C++ Maps::find

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.

find() runs in logarithmic time.


C++ Maps::insert

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 pos (where pos is really just a suggestion as to where val should go, since sets and maps are ordered), 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.

Related topics:
Map operators


C++ Maps::key_comp

key_comp
Syntax:
  key_compare key_comp() const;

The function key_comp() returns the function that compares keys.

key_comp() runs in constant time.

Related topics:
value_comp


C++ Maps::lower_bound

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.

lower_bound() runs in logarithmic time.

Related topics:
upper_bound


C++ Maps::max_size

max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size


C++ Maps::rbegin

rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current map.

rbegin() runs in constant time.


C++ Maps::rend

rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current map.

rend() runs in constant time.


C++ Maps::size

size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
(C++ Strings) resize


C++ Maps::swap

swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current map with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice


C++ Maps::upper_bound

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.

Related topics:
lower_bound


C++ Maps::value_comp

value_comp
Syntax:
  value_compare value_comp() const;

The value_comp() function returns the function that compares values.

value_comp() runs in constant time.

Related topics:
key_comp


C++ Multimaps

C++ Multimaps are like maps, in that they are sorted associative containers, but differ from maps in that they allow duplicate keys.

Display all entries for C++ Multimaps on one page, or view entries individually:

Container constructors & destructors | default methods to allocate, copy, and deallocate multimaps
Container operators | assign and compare multimaps
begin | returns an iterator to the beginning of the multimap
clear | removes all elements from the multimap
count | returns the number of elements matching a certain key
empty | true if the multimap has no elements
end | returns an iterator just past the last element of a multimap
equal_range | returns iterators to the first and just past the last elements matching a specific key
erase | removes elements from a multimap
find | returns an iterator to specific elements
insert | inserts items into a multimap
key_comp | returns the function that compares keys
lower_bound | returns an iterator to the first element greater than or equal to a certian value
max_size | returns the maximum number of elements that 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 | returns the number of items in the multimap
swap | swap the contents of this multimap with another
upper_bound | returns an iterator to the first element greater than a certain value
value_comp | returns the function that compares values


C++ Multimaps::Container constructors & destructors

Container constructors & destructors
Syntax:
  container();
  container( const container& c );
  ~container();

Every multimap has a default constructor, copy constructor, and destructor.

The default constructor takes no arguments, creates a new instance of that multimap, and runs in constant time. The default copy constructor runs in linear time and can be used to create a new multimap that is a copy of the given multimap c.

The default destructor is called when the multimap should be destroyed.

For example, the following code creates a pointer to a vector of integers and then uses the default multimap constructor to allocate a memory for a new vector:

 vector<int>* v;
 v = new vector<int>();

Related topics:
(C++ Strings) resize


C++ Multimaps::Container operators

Container operators
Syntax:
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one multimap to another takes linear time.

Two multimaps are equal if:

  1. Their size is the same, and
  2. Each member in location i in one multimap is equal to the the member in location i in the other multimap.

Comparisons among multimaps are done lexicographically.

Related topics:
(C++ Strings) String operators
(C++ Strings) at
(C++ Lists) merge
(C++ Lists) unique


C++ Multimaps::begin

begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the multimap. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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;
   }


C++ Multimaps::clear

clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the multimap. clear() runs in linear time.

Related topics:
(C++ Lists) erase


C++ Multimaps::count

count
Syntax:
  size_type count( const key_type& key );

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

count() should run in logarithmic time.


C++ Multimaps::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the multimap has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a multimap and display 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


C++ Multimaps::end

end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the multimap.

Note that before you can access the last element of the multimap using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.


C++ Multimaps::equal_range

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 a point just after the last element that contains key.


C++ Multimaps::erase

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.


C++ Multimaps::find

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.

find() runs in logarithmic time.


C++ Multimaps::insert

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

The function insert() either:
  • inserts val after the element at pos (where pos is really just a suggestion as to where val should go, since multisets and multimaps are ordered), and returns an iterator to that element.
  • inserts a range of elements from start to end.
  • inserts val into the multimap. The return value is an iterator to the element inserted, and a boolean describing whether an insertion took place.


C++ Multimaps::key_comp

key_comp
Syntax:
  key_compare key_comp() const;

The function key_comp() returns the function that compares keys.

key_comp() runs in constant time.

Related topics:
value_comp


C++ Multimaps::lower_bound

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.

lower_bound() runs in logarithmic time.

Related topics:
upper_bound


C++ Multimaps::max_size

max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size


C++ Multimaps::rbegin

rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current multimap.

rbegin() runs in constant time.


C++ Multimaps::rend

rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current multimap.

rend() runs in constant time.


C++ Multimaps::size

size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
(C++ Strings) resize


C++ Multimaps::swap

swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current multimap with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice


C++ Multimaps::upper_bound

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.

Related topics:
lower_bound


C++ Multimaps::value_comp

value_comp
Syntax:
  value_compare value_comp() const;

The value_comp() function returns the function that compares values.

value_comp() runs in constant time.

Related topics:
key_comp


C++ Multisets

C++ Multisets are like sets, in that they are associative containers containing a sorted set of objects, but differ in that they allow duplicate objects.

Display all entries for C++ Multisets on one page, or view entries individually:

Container constructors & destructors | default methods to allocate, copy, and deallocate multisets
Container operators | assign and compare multisets
begin | returns an iterator to the beginning of the multiset
clear | removes all elements from the multiset
count | returns the number of elements matching a certain key
empty | true if the multiset has no elements
end | returns an iterator just past the last element of a multiset
equal_range | returns iterators to the first and just past the last elements matching a specific key
erase | removes elements from a multiset
find | returns an iterator to specific elements
insert | inserts items into a multiset
key_comp | returns the function that compares keys
lower_bound | returns an iterator to the first element greater than or equal to a certian value
max_size | returns the maximum number of elements that the multiset can hold
rbegin | returns a reverse_iterator to the end of the multiset
rend | returns a reverse_iterator to the beginning of the multiset
size | returns the number of items in the multiset
swap | swap the contents of this multiset with another
upper_bound | returns an iterator to the first element greater than a certain value
value_comp | returns the function that compares values


C++ Multisets::Container constructors & destructors

Container constructors & destructors
Syntax:
  container();
  container( const container& c );
  ~container();

Every multiset has a default constructor, copy constructor, and destructor.

The default constructor takes no arguments, creates a new instance of that multiset, and runs in constant time. The default copy constructor runs in linear time and can be used to create a new multiset that is a copy of the given multiset c.

The default destructor is called when the multiset should be destroyed.

For example, the following code creates a pointer to a vector of integers and then uses the default multiset constructor to allocate a memory for a new vector:

 vector<int>* v;
 v = new vector<int>();

Related topics:
(C++ Strings) resize


C++ Multisets::Container operators

Container operators
Syntax:
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one multiset to another takes linear time.

Two multisets are equal if:

  1. Their size is the same, and
  2. Each member in location i in one multiset is equal to the the member in location i in the other multiset.

Comparisons among multisets are done lexicographically.

Related topics:
(C++ Strings) String operators
(C++ Strings) at
(C++ Lists) merge
(C++ Lists) unique


C++ Multisets::begin

begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the multiset. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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;
   }


C++ Multisets::clear

clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the multiset. clear() runs in linear time.

Related topics:
(C++ Lists) erase


C++ Multisets::count

count
Syntax:
  size_type count( const key_type& key );

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

count() should run in logarithmic time.


C++ Multisets::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the multiset has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a multiset and display 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


C++ Multisets::end

end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the multiset.

Note that before you can access the last element of the multiset using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.


C++ Multisets::equal_range

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 a point just after the last element that contains key.


C++ Multisets::erase

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.


C++ Multisets::find

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.

find() runs in logarithmic time.


C++ Multisets::insert

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

The function insert() either:
  • inserts val after the element at pos (where pos is really just a suggestion as to where val should go, since multisets and multimaps are ordered), and returns an iterator to that element.
  • inserts a range of elements from start to end.
  • inserts val into the multiset. The return value is an iterator to the element inserted, and a boolean describing whether an insertion took place.


C++ Multisets::key_comp

key_comp
Syntax:
  key_compare key_comp() const;

The function key_comp() returns the function that compares keys.

key_comp() runs in constant time.

Related topics:
value_comp


C++ Multisets::lower_bound

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.

lower_bound() runs in logarithmic time.

Related topics:
upper_bound


C++ Multisets::max_size

max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size


C++ Multisets::rbegin

rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current multiset.

rbegin() runs in constant time.


C++ Multisets::rend

rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current multiset.

rend() runs in constant time.


C++ Multisets::size

size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
(C++ Strings) resize


C++ Multisets::swap

swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current multiset with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice


C++ Multisets::upper_bound

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.

Related topics:
lower_bound


C++ Multisets::value_comp

value_comp
Syntax:
  value_compare value_comp() const;

The value_comp() function returns the function that compares values.

value_comp() runs in constant time.

Related topics:
key_comp


C++ Priority Queues

C++ Priority Queues are like queues, but the elements inside the the data structure are ordered by some predicate.

Display all entries for C++ Priority Queues on one page, or view entries individually:

Priority queue constructors | construct a new priority queue
empty | true if the priority queue has no elements
pop | removes the top element of a priority queue
push | adds an element to the end of the priority queue
size | returns the number of items in the priority queue
top | returns the top element of the priority queue


C++ Priority Queues::Priority queue constructors

Priority queue constructors
Syntax:
  priority_queue( const Compare& cmp = Compare(), const Container& c = Container() );
  priority_queue( input_iterator start, input_iterator end, const Compare& comp = Compare(), const Container& c = Container() );

Priority queues can be constructed with an optional compare function cmp' and an optional container c. If start and end are specified, the priority queue will be constructed with the elements between start and end.


C++ Priority Queues::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the priority queue has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a priority queue and display 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


C++ Priority Queues::pop

pop
Syntax:
  void pop();

The function pop() removes the top element of the priority queue and discards it.


C++ Priority Queues::push

push
Syntax:
  void push( const TYPE& val );

The function push() adds val to the end of the current priority queue.

For example, the following code uses the push() function to add ten integers to the end of a queue:

   queue<int> q;
   for( int i=0; i < 10; i++ )
     q.push(i);


C++ Priority Queues::size

size
Syntax:
  size_type size() const;

The size() function returns the number of elements in the current priority queue.

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
(C++ Multimaps) max_size
(C++ Strings) resize


C++ Priority Queues::top

top
Syntax:
  TYPE& top();

The function top() returns a reference to the top element of the priority queue.

For example, the following code removes all of the elements from a stack and uses top() to display them:

   while( !s.empty() ) {
     cout << s.top() << " ";
     s.pop();
   }

Related topics:
pop


C++ Queues

The C++ Queue is a container adapter that gives the programmer a FIFO (first-in, first-out) data structure.

Display all entries for C++ Queues on one page, or view entries individually:

Queue constructor | construct a new queue
back | returns a reference to last element of a queue
empty | true if the queue has no elements
front | returns a reference to the first element of a queue
pop | removes the top element of a queue
push | adds an element to the end of the queue
size | returns the number of items in the queue


C++ Queues::Queue constructor

Queue constructor
Syntax:
  queue();
  queue( const Container& con );

Queues have an empty constructor and a constructor that can be used to specify a container type.


C++ Queues::back

back
Syntax:
  TYPE& back();
  const TYPE& back() const;

The back() function returns a reference to the last element in the queue.

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

The back() function runs in constant time.

Related topics:
front
(C++ Lists) pop_back


C++ Queues::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the queue has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a queue and display 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


C++ Queues::front

front
Syntax:
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the queue, and runs in constant time.

Related topics:
back
(C++ Lists) pop_front
(C++ Lists) push_front


C++ Queues::pop

pop
Syntax:
  void pop();

The function pop() removes the top element of the queue and discards it.

Related topics:
push
(C++ Priority Queues) top


C++ Queues::push

push
Syntax:
  void push( const TYPE& val );

The function push() adds val to the end of the current queue.

For example, the following code uses the push() function to add ten integers to the end of a queue:

   queue<int> q;
   for( int i=0; i < 10; i++ )
     q.push(i);


C++ Queues::size

size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
(C++ Multimaps) max_size
(C++ Strings) resize


C++ Sets

The C++ Set is an associative container that contains a sorted set of unique objects.

Display all entries for C++ Sets on one page, or view entries individually:

Container constructors & destructors | default methods to allocate, copy, and deallocate sets
Container operators | assign and compare sets
begin | returns an iterator to the beginning of the set
clear | removes all elements from the set
count | returns the number of elements matching a certain key
empty | true if the set has no elements
end | returns an iterator just past the last element of a set
equal_range | returns iterators to the first and just past the last elements matching a specific key
erase | removes elements from a set
find | returns an iterator to specific elements
insert | insert items into a set
key_comp | returns the function that compares keys
lower_bound | returns an iterator to the first element greater than or equal to a certian value
max_size | returns 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 | returns the number of items in the set
swap | swap the contents of this set with another
upper_bound | returns an iterator to the first element greater than a certain value
value_comp | returns the function that compares values


C++ Sets::Container constructors & destructors

Container constructors & destructors
Syntax:
  container();
  container( const container& c );
  ~container();

Every set has a default constructor, copy constructor, and destructor.

The default constructor takes no arguments, creates a new instance of that set, and runs in constant time. The default copy constructor runs in linear time and can be used to create a new set that is a copy of the given set c.

The default destructor is called when the set should be destroyed.

For example, the following code creates a pointer to a vector of integers and then uses the default set constructor to allocate a memory for a new vector:

 vector<int>* v;
 v = new vector<int>();

Related topics:
(C++ Strings) resize


C++ Sets::Container operators

Container operators
Syntax:
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one set to another takes linear time.

Two sets are equal if:

  1. Their size is the same, and
  2. Each member in location i in one set is equal to the the member in location i in the other set.

Comparisons among sets are done lexicographically.

Related topics:
(C++ Strings) String operators
(C++ Strings) at
(C++ Lists) merge
(C++ Lists) unique


C++ Sets::begin

begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the set. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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;
   }


C++ Sets::clear

clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the set. clear() runs in linear time.

Related topics:
(C++ Lists) erase


C++ Sets::count

count
Syntax:
  size_type count( const key_type& key );

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

count() should run in logarithmic time.


C++ Sets::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the set has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a set and display 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


C++ Sets::end

end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the set.

Note that before you can access the last element of the set using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.


C++ Sets::equal_range

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 a point just after the last element that contains key.


C++ Sets::erase

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.


C++ Sets::find

find
Syntax:
  iterator find( const key_type& key );

The find() function returns an iterator to key, or an iterator to the end of the set if key is not found.

find() runs in logarithmic time.


C++ Sets::insert

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 pos (where pos is really just a suggestion as to where val should go, since sets and maps are ordered), 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.

Related topics:
(C++ Maps) Map operators


C++ Sets::key_comp

key_comp
Syntax:
  key_compare key_comp() const;

The function key_comp() returns the function that compares keys.

key_comp() runs in constant time.

Related topics:
value_comp


C++ Sets::lower_bound

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.

lower_bound() runs in logarithmic time.

Related topics:
upper_bound


C++ Sets::max_size

max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size


C++ Sets::rbegin

rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current set.

rbegin() runs in constant time.


C++ Sets::rend

rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current set.

rend() runs in constant time.


C++ Sets::size

size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
(C++ Strings) resize


C++ Sets::swap

swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current set with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice


C++ Sets::upper_bound

upper_bound
Syntax:
  iterator upper_bound( const key_type& key );

The function upper_bound() returns an iterator to the first element in the set with a key greater than key.

Related topics:
lower_bound


C++ Sets::value_comp

value_comp
Syntax:
  value_compare value_comp() const;

The value_comp() function returns the function that compares values.

value_comp() runs in constant time.

Related topics:
key_comp


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.

Display all entries for C++ Stacks on one page, or view entries individually:

Stack constructors | construct a new stack
empty | true if the stack has no elements
pop | removes the top element of a stack
push | adds an element to the top of the stack
size | returns the number of items in the stack
top | returns the top element of the stack


C++ Stacks::Stack constructors

Stack constructors
Syntax:
  stack();
  stack( const Container& con );

Stacks have an empty constructor and a constructor that can be used to specify a container type.


C++ Stacks::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the stack has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a stack and display 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


C++ Stacks::pop

pop
Syntax:
  void pop();

The function pop() removes the top element of the stack and discards it.

Related topics:
(C++ Priority Queues) push
top


C++ Stacks::push

push
Syntax:
  void push( const TYPE& val );

The function push() adds val to the top of the current stack.

For example, the following code uses the push() function to add ten integers to the top of a stack:

   stack<int> s;
   for( int i=0; i < 10; i++ )
     s.push(i);

Related topics:
pop


C++ Stacks::size

size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
(C++ Multimaps) max_size
(C++ Strings) resize


C++ Stacks::top

top
Syntax:
  TYPE& top();

The function top() returns a reference to the top element of the stack.

For example, the following code removes all of the elements from a stack and uses top() to display them:

   while( !s.empty() ) {
     cout << s.top() << " ";
     s.pop();
   }

Related topics:
pop


C++ Strings

Display all entries for C++ Strings on one page, or view entries individually:

String constructors | create strings from arrays of characters and other strings
String operators | concatenate strings, assign strings, use strings for I/O, compare strings
append | append characters and strings onto a string
assign | give a string values from strings of characters and other C++ strings
at | returns an element at a specific location
begin | returns an iterator to the beginning of the string
c_str | returns a standard C character array version of the string
capacity | returns the number of elements that the string can hold
clear | removes all elements from the string
compare | compares two strings
copy | copies characters from a string into an array
data | returns a pointer to the first character of a string
empty | true if the string has no elements
end | returns an iterator just past the last element of a string
erase | removes elements from a string
find | find characters in the string
find_first_not_of | find first absence of characters
find_first_of | find first occurrence of characters
find_last_not_of | find last absence of characters
find_last_of | find last occurrence of characters
getline | read data from an I/O stream into a string
insert | insert characters into a string
length | returns the length of the string
max_size | returns the maximum number of elements that the string can hold
push_back | add an element to the end of the string
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 minimum capacity of the string
resize | change the size of the string
rfind | find the last occurrence of a substring
size | returns the number of items in the string
substr | returns a certain substring
swap | swap the contents of this string with another


C++ Strings::String constructors

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

The string constructors create a new string containing:

  • nothing; an empty string,
  • a copy of the given string s,
  • 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
  • a string of characterss denoted by the start and end iterators

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

The string constructors usually run in linear time, except the empty constructor, which runs in constant time.


C++ Strings::String operators

String operators
Syntax:
  bool operator==(const string& c1, const string& c2);
  bool operator!=(const string& c1, const string& c2);
  bool operator<(const string& c1, const string& c2);
  bool operator>(const string& c1, const string& c2);
  bool operator<=(const string& c1, const string& c2);
  bool operator>=(const string& c1, const string& c2);
  string operator+(const string& s1, const string& s2 );
  string operator+(const char* s, const string& s2 );
  string operator+( char c, const string& s2 );
  string operator+( const string& s1, const char* s );
  string operator+( const string& s1, char c );
  ostream& operator<<( ostream& os, const string& s );
  istream& operator>>( istream& is, string& s );
  string& operator=( const string& s );
  string& operator=( const char* s );
  string& operator=( char ch );
  char& operator[]( size_type index );

C++ strings can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one string to another takes linear time.

Two strings are equal if:

  1. Their size is the same, and
  2. Each member in location i in one string is equal to the the member in location i in the other string.

Comparisons among strings are done lexicographically.

In addition to these normal (C++ Multimaps) Container operators, strings can also be concatenated with the + operator and fed to the C++ I/O stream classes with the << and >> operators.

For example, the following code concatenates two strings and displays the result:

 string s1 = "Now is the time...";
 string s2 = "for all good men...";
 string s3 = s1 + s2;
 cout << "s3 is " << s3 << endl;

Furthermore, strings can be assigned values that are other strings, character arrays, or even single characters. The following code is perfectly valid:

 char ch = 'N';
 string s = ch;

Individual characters of a string can be examined with the [] operator, which runs in constant time.

Related topics:
(C++ Multimaps) Container operators
c_str
compare
data


C++ Strings::append

append
Syntax:
  string& append( const string& str );
  string& append( const char* str );
  string& append( const string& str, size_type index, size_type len );
  string& append( const char* str, size_type num );
  string& append( size_type num, char ch );
  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 uses append() to add 10 copies of the '!' character to a string:

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

That code displays:

   Hello World!!!!!!!!!!

In the next example, append() is used to concatenate a substring of one string onto another string:

 string str1 = "Eventually I stopped caring...";
 string str2 = "but that was the '80s so nobody noticed.";
 str1.append( str2, 25, 15 );
 cout << "str1 is " << str1 << endl;

When run, the above code displays:

 str1 is Eventually I stopped caring...nobody noticed.


C++ Strings::assign

assign
Syntax:
  void assign( size_type num, const char& val );
  void assign( input_iterator start, input_iterator end );
  string& assign( const string& str );
  string& assign( const char* str );
  string& assign( const char* str, size_type num );
  string& assign( const string& str, size_type index, size_type len );
  string& assign( size_type num, const char& ch );

The deafult assign() function gives the current string the values from start to end, or gives it num copies of val.

In addition to the normal (C++ Lists) assign() functionality that all C++ containers have, strings possess an assign() function that also allows them to:

  • assign str to the current string,
  • assign the first num characters of str to the current string,
  • assign a substring of str starting at index that is len characters long 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

This function will destroy the previous contents of the string.

Related topics:
(C++ Lists) assign


C++ Strings::at

at
Syntax:
  TYPE& at( size_type loc );
  const TYPE& at( size_type loc ) const;

The at() function returns a reference to the element in the string at index loc. The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the string.

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:
(C++ Multimaps) Container operators
(C++ Double-ended Queues) Container operators


C++ Strings::begin

begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the string. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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;
   }


C++ Strings::c_str

c_str
Syntax:
  const char* c_str();

The function c_str() returns a const pointer to a regular C string, identical to the current string. The returned string is null-terminated.

Note that since the returned pointer is of type (C/C++ Keywords) const, the character data that c_str() returns cannot be modified.


C++ Strings::capacity

capacity
Syntax:
  size_type capacity() const;

The capacity() function returns the number of elements that the string can hold before it will need to allocate more space.

For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size, the other method calls the reserve function to achieve a similar goal:

 vector<int> v1(10);
 cout << "The capacity of v1 is " << v1.capacity() << endl;
 vector<int> v2;
 v2.reserve(20);
 cout << "The capacity of v2 is " << v2.capacity() << endl;

When run, the above code produces the following output:

 The capacity of v1 is 10
 The capacity of v2 is 20

C++ containers are designed to grow in size dynamically. This frees the programmer from having to worry about storing an arbitrary number of elements in a container. However, sometimes the programmer can improve the performance of her program by giving hints to the compiler about the size of the containers that the program will use. These hints come in the form of the reserve() function and the constructor used in the above example, which tell the compiler how large the container is expected to get.

The capacity() function runs in constant time.


C++ Strings::clear

clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the string. clear() runs in linear time.

Related topics:
(C++ Lists) erase


C++ Strings::compare

compare
Syntax:
  int compare( const string& str );
  int compare( const char* str );
  int compare( size_type index, size_type length, const string& str );
  int compare( size_type index, size_type length, const 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.

For example, the following code uses compare() to compare four strings with eachother:

 string names[] = {"Homer", "Marge", "3-eyed fish", "inanimate carbon rod"};
 for( int i = 0; i < 4; i++ ) {
   for( int j = 0; j < 4; j++ ) {
     cout << names[i].compare( names[j] ) << " ";
   }
   cout << endl;
 }

Data from the above code was used to generate this table, which shows how the various strings compare to eachother:

 | Homer | Marge | 3-eyed fish | inanimate carbon rod
"Homer".compare( x ) | 0 | -1 | 1 | -1
"Marge".compare( x ) | 1 | 0 | 1 | -1
"3-eyed fish".compare( x ) | -1 | -1 | 0 | -1
"inanimate carbon rod".compare( x ) | 1 | 1 | 1 | 0

Related topics:
String operators


C++ Strings::copy

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

The copy() function copies num characters of the current string (starting at index if it's specified, 0 otherwise) into str.

The return value of copy() is the number of characters copied.

For example, the following code uses copy() to extract a substring of a string into an array of characters:

 char buf[30];
 memset( buf, '/0', 30 );
 string str = "Trying is the first step towards failure.";
 str.copy( buf, 24 );
 cout << buf << endl;

When run, this code displays:

 Trying is the first step

Note that before calling copy(), we first call (Standard C String and Character) memset() to fill the destination array with copies of the NULL character. This step is included to make sure that the resulting array of characters is NULL-terminated.

Related topics:
substr


C++ Strings::data

data
Syntax:
  const char *data();

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


C++ Strings::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the string has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a string and display 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


C++ Strings::end

end
Syntax:
  iterator end();
  const_iterator end() const;

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

Note that before you can access the last element of the string using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.


C++ Strings::erase

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

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 ''

erase() runs in linear time.

Related topics:
insert


C++ Strings::find

find
Syntax:
  size_type find( const 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;


C++ Strings::find_first_not_of

find_first_not_of
Syntax:
  size_type find_first_not_of( const 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.

For example, the following code searches a string of text for the first character that is not a lower-case character, space, comma, or hypen:

 string lower_case = "abcdefghijklmnopqrstuvwxyz ,-";
 string str = "this is the lower-case part, AND THIS IS THE UPPER-CASE PART";
 cout << "first non-lower-case letter in str at: " << str.find_first_not_of(lower_case) << endl;

When run, find_first_not_of() finds the first upper-case letter in str at index 29 and displays this output:

 first non-lower-case letter in str at: 29


C++ Strings::find_first_of

find_first_of
Syntax:
  size_type find_first_of( const 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.


C++ Strings::find_last_not_of

find_last_not_of
Syntax:
  size_type find_last_not_of( const 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.

For example, the following code searches for the last non-lower-case character in a mixed string of characters:

 string lower_case = "abcdefghijklmnopqrstuvwxyz";
 string str = "abcdefgABCDEFGhijklmnop";
 cout << "last non-lower-case letter in str at: " << str.find_last_not_of(lower_case) << endl;

This code displays the following output:

 last non-lower-case letter in str at: 13


C++ Strings::find_last_of

find_last_of
Syntax:
  size_type find_last_of( const 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.


C++ Strings::getline

getline
Syntax:
  istream& getline( istream& is, string& s, char delimiter = '/n' );

The C++ string class defines the global function getline() to read strings from and I/O stream. The getline() function, which is not part of the string class, reads a line from is and stores it into s. If a character delimiter is specified, then getline() will use delimiter to decide when to stop reading data.

For example, the following code reads a line of text from STDIN and displays it to STDOUT:

 string s;
 getline( cin, s );
 cout << "You entered " << s << endl;

Related topics:
(C++ I/O) get
(C++ I/O) getline


C++ Strings::insert

insert
Syntax:
  iterator insert( iterator i, const char& ch );
  string& insert( size_type index, const string& str );
  string& insert( size_type index, const char* str );
  string& insert( size_type index1, const string& str, size_type index2, size_type num );
  string& insert( size_type index, const char* str, size_type num );
  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.


C++ Strings::length

length
Syntax:
  size_type length() const;

The length() function returns the number of elements in the current string, performing the same role as the size() function.

Related topics:
size


C++ Strings::max_size

max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size


C++ Strings::push_back

push_back
Syntax:
  void push_back( const TYPE& val );

The push_back() function appends val to the end of the string.

For example, the following code puts 10 integers into a list:

   list<int> the_list;
   for( int i = 0; i < 10; i++ )
     the_list.push_back( i );

When displayed, the resulting list would look like this:

 0 1 2 3 4 5 6 7 8 9

push_back() runs in constant time.

Related topics:
(C++ Lists) assign
(C++ Lists) insert
(C++ Lists) pop_back
(C++ Lists) push_front


C++ Strings::rbegin

rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

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

rbegin() runs in constant time.


C++ Strings::rend

rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current string.

rend() runs in constant time.


C++ Strings::replace

replace
Syntax:
  string& replace( size_type index, size_type num, const string& str );
  string& replace( size_type index1, size_type num1, const string& str, size_type index2, size_type num2 );
  string& replace( size_type index, size_type num, const char* str );
  string& replace( size_type index, size_type num1, const char* str, size_type num2 );
  string& replace( size_type index, size_type num1, size_type num2, char ch );
  string& replace( iterator start, iterator end, const string& str );
  string& replace( iterator start, iterator end, const char* str );
  string& replace( iterator start, iterator end, const char* str, size_type num );
  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


C++ Strings::reserve

reserve
Syntax:
  void reserve( size_type size );

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

reserve() runs in linear time.

Related topics:
capacity


C++ Strings::resize

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

The function resize() changes the size of the string to size. If val is specified then any newly-created elements will be initialized to have a value of val.

This function runs in linear time.

Related topics:
(C++ Multimaps) Container constructors & destructors
capacity
size


C++ Strings::rfind

rfind
Syntax:
  size_type rfind( const 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 ch in the current string, doing a reverse 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;


C++ Strings::size

size
Syntax:
  size_type size() const;

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


C++ Strings::substr

substr
Syntax:
  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

Related topics:
copy


C++ Strings::swap

swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current string with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice


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.

Display all entries for C++ Vectors on one page, or view entries individually:

Container constructors | create vectors and initialize them with some data
Container operators | compare, assign, and access elements of a vector
assign | assign elements to a vector
at | returns an element at a specific location
back | returns a reference to last element of a vector
begin | returns an iterator to the beginning of the vector
capacity | returns the number of elements that the vector can hold
clear | removes all elements from the vector
empty | true if the vector has no elements
end | returns an iterator just past the last element of a vector
erase | removes elements from a vector
front | returns a reference to the first element of a vector
insert | inserts elements into the vector
max_size | returns the maximum number of elements that the vector can hold
pop_back | removes the last element of a vector
push_back | add 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 number of items in the vector
swap | swap the contents of this vector with another


C++ Vectors::Container constructors

Container constructors
Syntax:
  container();
  container( const container& c );
  container( size_type num, const TYPE& val = TYPE() );
  container( input_iterator start, input_iterator end );
  ~container();

The default vector constructor takes no arguments, creates a new instance of that vector.

The second constructor is a default copy constructor that can be used to create a new vector that is a copy of the given vector c.

The third constructor creates a vector with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a vector consisting of five copies of the integer 42:

 vector<int> v1( 5, 42 );

The last constructor creates a vector that is initialized to contain the elements between start and end. For example:

 // create a vector of random integers
 cout << "original vector: ";
 vector<int> v;
 for( int i = 0; i < 10; i++ ) {
   int num = (int) rand() % 10;
   cout << num << " ";
   v.push_back( num );
 }
 cout << endl;
 // find the first element of v that is even
 vector<int>::iterator iter1 = v.begin();
 while( iter1 != v.end() && *iter1 % 2 != 0 ) {
   iter1++;
 }
 // find the last element of v that is even
 vector<int>::iterator iter2 = v.end();
 do {
   iter2--;
 } while( iter2 != v.begin() && *iter2 % 2 != 0 );
 cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;
 cout << "new vector: ";
 vector<int> v2( iter1, iter2 );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, this code displays the following output:

 original vector: 1 9 7 9 2 7 2 1 9 8
 first even number: 2, last even number: 8
 new vector: 2 7 2 1 9

All of these constructors run in linear time except the first, which runs in constant time.

The default destructor is called when the vector should be destroyed.


C++ Vectors::Container operators

Container operators
Syntax:
  TYPE& operator[]( size_type index );
  const TYPE& operator[]( size_type index ) const;
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Individual elements of a vector can be examined with the [] operator.

Performing a comparison or assigning one vector to another takes linear time. The [] operator runs in constant time.

Two `containers` 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.

For example, the following code uses the [] operator to access all of the elements of a vector:

 vector<int> v( 5, 1 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << "Element " << i << " is " << v[i] << endl;
 }

Related topics:
at


C++ Vectors::assign

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

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.

For example, the following code uses assign() to put 10 copies of the integer 42 into a vector:

 vector<int> v;
 v.assign( 10, 42 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << v[i] << " ";
 }
 cout << endl;

The above code displays the following output:

 42 42 42 42 42 42 42 42 42 42

The next example shows how assign() can be used to copy one vector to another:

 vector<int> v1;
 for( int i = 0; i < 10; i++ ) {
   v1.push_back( i );
 }
 vector<int> v2;
 v2.assign( v1.begin(), v1.end() );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, the above code displays the following output:

 0 1 2 3 4 5 6 7 8 9

Related topics:
(C++ Strings) assign
insert
push_back
(C++ Lists) push_front


C++ Vectors::at

at
Syntax:
  TYPE& at( size_type loc );
  const TYPE& at( size_type loc ) const;

The at() function returns a reference to the element in the vector at index 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:
(C++ Multimaps) Container operators
Container operators


C++ Vectors::back

back
Syntax:
  TYPE& back();
  const TYPE& back() const;

The back() function returns a reference to the last element in the 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

The back() function runs in constant time.


C++ Vectors::begin

begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the vector. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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;
   }


C++ Vectors::capacity

capacity
Syntax:
  size_type capacity() const;

The capacity() function returns the number of elements that the vector can hold before it will need to allocate more space.

For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size, the other method calls the reserve function to achieve a similar goal:

 vector<int> v1(10);
 cout << "The capacity of v1 is " << v1.capacity() << endl;
 vector<int> v2;
 v2.reserve(20);
 cout << "The capacity of v2 is " << v2.capacity() << endl;

When run, the above code produces the following output:

 The capacity of v1 is 10
 The capacity of v2 is 20

C++ containers are designed to grow in size dynamically. This frees the programmer from having to worry about storing an arbitrary number of elements in a container. However, sometimes the programmer can improve the performance of her program by giving hints to the compiler about the size of the containers that the program will use. These hints come in the form of the reserve() function and the constructor used in the above example, which tell the compiler how large the container is expected to get.

The capacity() function runs in constant time.


C++ Vectors::clear

clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the vector. clear() runs in linear time.

Related topics:
erase


C++ Vectors::empty

empty
Syntax:
  bool empty() const;

The empty() function returns true if the vector has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a vector and display 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


C++ Vectors::end

end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the vector.

Note that before you can access the last element of the vector using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.


C++ Vectors::erase

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.

The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, dequeues, and strings. The multiple-element version of erase always takes linear time.

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

In the next example, erase() is called with two iterators to delete a range of elements from a vector:

 // 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 );
 }
 // display the complete vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;
 // use erase to remove all but the first two and last three elements
 // of the vector
 alphaVector.erase( alphaVector.begin()+2, alphaVector.end()-3 );
 // display the modified vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;

When run, the above code displays:

 ABCDEFGHIJ
 ABHIJ

Related topics:
clear
insert
pop_back
(C++ Lists) pop_front
(C++ Lists) remove
(C++ Lists) remove_if


C++ Vectors::front

front
Syntax:
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the vector, and runs in constant time.

Related topics:
back
(C++ Lists) pop_front
(C++ Lists) push_front


C++ Vectors::insert

insert
Syntax:
  iterator insert( iterator loc, const TYPE& val );
  void insert( iterator loc, size_type num, const TYPE& val );
  template<TYPE> void insert( iterator loc, input_iterator start, input_iterator end );

The insert() function either:

  • inserts val before loc, returning an iterator to the element inserted,
  • 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

Related topics:
assign
erase
(C++ Lists) merge
push_back
(C++ Lists) push_front
(C++ Lists) splice


C++ Vectors::max_size

max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size


C++ Vectors::pop_back

pop_back
Syntax:
  void pop_back();

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

pop_back() runs in constant time.

Related topics:
back
erase
(C++ Lists) pop_front
push_back


C++ Vectors::push_back

push_back
Syntax:
  void push_back( const TYPE& val );

The push_back() function appends val to the end of the vector.

For example, the following code puts 10 integers into a list:

   list<int> the_list;
   for( int i = 0; i < 10; i++ )
     the_list.push_back( i );

When displayed, the resulting list would look like this:

 0 1 2 3 4 5 6 7 8 9

push_back() runs in constant time.

Related topics:
assign
insert
pop_back
(C++ Lists) push_front


C++ Vectors::rbegin

rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current vector.

rbegin() runs in constant time.


C++ Vectors::rend

rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current vector.

rend() runs in constant time.


C++ Vectors::reserve

reserve
Syntax:
  void reserve( size_type size );

The reserve() function sets the capacity of the vector to at least size.

reserve() runs in linear time.

Related topics:
capacity


C++ Vectors::resize

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

The function resize() changes the size of the vector to size. If val is specified then any newly-created elements will be initialized to have a value of val.

This function runs in linear time.

Related topics:
(C++ Multimaps) Container constructors & destructors
capacity
size


C++ Vectors::size

size
Syntax:
  size_type size() const;

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

Related topics:
capacity
empty
(C++ Strings) length
max_size
resize


C++ Vectors::swap

swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current vector with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice


C/C++ Keywords

Display all entries for C/C++ Keywords on one page, or view entries individually:

asm | insert an assembly instruction
auto | declare a local variable
bool | declare a boolean variable
break | break out of a loop
case | a block of code in a switch statement
catch | handles exceptions from throw
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 | make memory available
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 | optimize calls to short functions
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 | define 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 | import complete or partial namespaces into the current scope
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 construct


C/C++ Keywords::asm

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 );


C/C++ Keywords::auto

auto

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

Related topics:
register


C/C++ Keywords::bool

bool

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

For example, the following code declares a boolean variable called done, initializes it to false, and then loops until that variable is set to true.

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

Also see the data types page.


C/C++ Keywords::break

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.


C/C++ Keywords::case

case

The case keyword is used to test a variable against a certain value in a switch statement.


C/C++ Keywords::catch

catch

The catch statement handles exceptions generated by the throw statement.


C/C++ Keywords::char

char

The char keyword is used to declare character variables. For more information about variable types, see the data types page.


C/C++ Keywords::class

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();
   };


C/C++ Keywords::const

const

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


C/C++ Keywords::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.


C/C++ Keywords::continue

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 << " ";
   }


C/C++ Keywords::default

default

A default case in the switch statement.


C/C++ Keywords::delete

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:
(Standard C Memory) free
(Standard C Memory) malloc
new


C/C++ Keywords::do

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.


C/C++ Keywords::double

double

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


C/C++ Keywords::dynamic_cast

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.


C/C++ Keywords::else

else

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

Related topics:
if


C/C++ Keywords::enum

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;
   }


C/C++ Keywords::explicit

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.


C/C++ Keywords::extern

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.


C/C++ Keywords::false

false

The Boolean value of "false".


C/C++ Keywords::float

float

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


C/C++ Keywords::for

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!
   }


C/C++ Keywords::friend

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.

Related topics:
class


C/C++ Keywords::goto

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


C/C++ Keywords::if

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.


C/C++ Keywords::inline

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, switch statements, 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.


C/C++ Keywords::int

int

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


C/C++ Keywords::long

long

The long keyword is a data type modifier that is used to declare long integer variables. For more information on long, see the data types page.


C/C++ Keywords::mutable

mutable

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

Related topics:
const


C/C++ Keywords::namespace

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;
     ...
   }

Related topics:
using


C/C++ Keywords::new

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
(Standard C Memory) free
(Standard C Memory) malloc


C/C++ Keywords::operator

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.

Related topics:
this


C/C++ Keywords::private

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.


C/C++ Keywords::protected

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.


C/C++ Keywords::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.


C/C++ Keywords::register

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


C/C++ Keywords::reinterpret_cast

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.


C/C++ Keywords::return

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.


C/C++ Keywords::short

short

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


C/C++ Keywords::signed

signed

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


C/C++ Keywords::sizeof

sizeof

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


C/C++ Keywords::static

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.


C/C++ Keywords::static_cast

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.


C/C++ Keywords::struct

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;
   };


C/C++ Keywords::switch

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;
   }


C/C++ Keywords::template

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, the following code uses a template to define a generic swap function that can swap two variables of any type:

   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 );
   }

Related topics:
typename


C/C++ Keywords::this

this

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


C/C++ Keywords::throw

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. This statement, 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;
   }


C/C++ Keywords::true

true

The Boolean value of "true".


C/C++ Keywords::try

try

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


C/C++ Keywords::typedef

typedef
Syntax:
  typedef existing-type new-type;

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


C/C++ Keywords::typeid

typeid
Syntax:
  typeid( object );

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


C/C++ Keywords::typename

typename

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


C/C++ Keywords::union

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

A union is like a class, 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;
   };


C/C++ Keywords::unsigned

unsigned

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


C/C++ Keywords::using

using

The using keyword is used to import a namespace (or parts of a namespace) into the current scope.

For example, the following code imports the entire std namespace into the current scope so that items within that namespace can be used without a preceeding "std::".

 using namespace std;

Alternatively, the next code snippet just imports a single element of the std namespace into the current namespace:

 using std::cout;

Related topics:
namespace


C/C++ Keywords::virtual

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 virtual 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 virtual function run.

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

Related topics:
class


C/C++ Keywords::void

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.


C/C++ Keywords::volatile

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.


C/C++ Keywords::wchar_t

wchar_t

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


C/C++ Keywords::while

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;
     }
   }


C/C++ Pre-processor Commands

Display all entries for C/C++ Pre-processor Commands on one page, or view entries individually:

#, ## | manipulate 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 | used to undefine variables
Predefined preprocessor variables | miscellaneous preprocessor variables


C/C++ 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.

Related topics:
#define


C/C++ Pre-processor Commands::#define

#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.


C/C++ Pre-processor Commands::#error

#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.


C/C++ Pre-processor Commands::#if, #ifdef, #ifndef, #else, #elif, #endif

#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 and removing a million "cout"s in your code.

Related topics:
#define


C/C++ Pre-processor Commands::#include

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

This command slurps in a file and inserts it at the current location. The main difference between the syntax of the two items 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.


C/C++ Pre-processor Commands::#line

#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".


C/C++ Pre-processor Commands::#pragma

#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.


C/C++ Pre-processor Commands::#undef

#undef

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

Related topics:
#define


C/C++ Pre-processor Commands::Predefined preprocessor variables

Predefined preprocessor 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++.


Miscellaneous C++

Display all entries for Miscellaneous C++ on one page, or view entries individually:

auto_ptr create pointers that automatically destroy objects


Miscellaneous C++::auto_ptr

auto_ptr
Syntax:
  #include<memory>
  auto_ptr<class TYPE> name

The auto_ptr class allows the programmer to create pointers that point to other objects. When auto_ptr pointers are destroyed, the objects to which they point are also destroyed. The auto_ptr class supports normal pointer operations like =, *, and ->, as well as two functions TYPE* get() and TYPE* release(). The get() function returns a pointer to the object that the auto_ptr points to. The release() function acts similarily to the get() function, but also relieves the auto_ptr of its memory destruction duties. When an auto_ptr that has been released goes out of scope, it will not call the destructor of the object that it points to.

 #include <memory>
 using namespace std;
 class MyClass {
 public:
   MyClass() { // nothing }
   ~MyClass() { // nothing }
   void myFunc() { // nothing }
 };
 int main() {
   auto_ptr<MyClass> ptr1(new MyClass), ptr2;
   ptr2 = ptr1;
   ptr2->myFunc();
   MyClass* ptr = ptr2.get();
   ptr->myFunc();
   return 0;
 }


Other Standard C Functions

Display all entries for Other Standard C Functions on one page, or view entries individually:

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

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.


Other Standard C Functions::assert

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


Other Standard C Functions::atexit

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 non-zero on failure.


Other Standard C Functions::bsearch

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


Other Standard C Functions::exit

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.


Other Standard C Functions::getenv

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


Other Standard C Functions::longjmp

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


Other Standard C Functions::qsort

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


Other Standard C Functions::raise

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


Other Standard C Functions::rand

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


Other Standard C Functions::setjmp

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


Other Standard C Functions::signal

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.

Related topics:
raise


Other Standard C Functions::srand

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
(Standard C Date & Time) time


Other Standard C Functions::system

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.


Other Standard C Functions::va_arg

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.


Standard C Date & Time

Display all entries for Standard C Date & Time on one page, or view entries individually:

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
setlocale | sets the current locale
strftime | returns individual elements of the date and time
time | returns the current calendar time of the system


Standard C Date & Time::asctime

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

An example:

   Mon Jun 26 12:03:53 2000


Standard C Date & Time::clock

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.)


Standard C Date & Time::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

using ctime() is equivalent to

   asctime( localtime( tp ) );


Standard C Date & Time::difftime

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

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


Standard C Date & Time::gmtime

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. Watch out for static return.


Standard C Date & Time::localtime

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

The function localtime() converts calendar time time into local time. Watch out for the static return.


Standard C Date & Time::mktime

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.


Standard C Date & Time::setlocale

setlocale
Syntax:
  #include <locale.h>
  char *setlocale( int category, const char * locale );

The setlocale() function is used to set and retrieve the current locale. If locale is NULL, the current locale is returned. Otherwise, locale is used to set the locale for the given category.

category can have the following values:

Value | Description
LC_ALL | All of the locale
LC_TIME | Date and time formatting
LC_NUMERIC | Number formatting
LC_COLLATE | String collation and regular expression matching
LC_CTYPE | Regular expression matching, conversion, case-sensitive comparison, wide character functions, and character classification.
LC_MONETARY | For monetary formatting
LC_MESSAGES | For natural language messages

Related topics:
(Standard C String and Character) strcoll


Standard C Date & Time::strftime

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.


Standard C Date & Time::time

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:
asctime
clock
ctime
difftime
gmtime
localtime
mktime
(Other Standard C Functions) srand
strftime


Standard C I/O

Display all entries for Standard C I/O on one page, or view entries individually:

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, and vsprintf | write formatted output with variable argument lists


Standard C I/O::clearerr

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.


Standard C I/O::fclose

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.


Standard C I/O::feof

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.


Standard C I/O::ferror

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.


Standard C I/O::fflush

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();


Standard C I/O::fgetc

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.


Standard C I/O::fgetpos

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.


Standard C I/O::fgets

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.


Standard C I/O::fopen

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 );


Standard C I/O::fprintf

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 );


Standard C I/O::fputc

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.


Standard C I/O::fputs

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.


Standard C I/O::fread

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. You can use feof() or ferror() to figure out if an error occurs.


Standard C I/O::freopen

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.


Standard C I/O::fscanf

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.


Standard C I/O::fseek

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):

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

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.


Standard C I/O::fsetpos

fsetpos
Syntax:
  #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.


Standard C I/O::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.


Standard C I/O::fwrite

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.


Standard C I/O::getc

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 );
   }


Standard C I/O::getchar

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.


Standard C I/O::gets

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.


Standard C I/O::perror

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.


Standard C I/O::printf

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.


Standard C I/O::putc

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.


Standard C I/O::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


Standard C I/O::puts

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.


Standard C I/O::remove

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


Standard C I/O::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


Standard C I/O::rewind

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


Standard C I/O::scanf

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.


Standard C I/O::setbuf

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 be BUFSIZ characters long.


Standard C I/O::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


Standard C I/O::sprintf

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" );

Note that sprintf() does the opposite of a function like (Standard C String and Character) atoi() -- where (Standard C String and Character) atoi() converts a string into a number, sprintf() can be used to convert a number into a string.

For example, the following code uses sprintf() to convert an integer into a string of characters:

   char result[100];
   int num=24;
   sprintf( result, "%d", num );

Related topics:
(Standard C String and Character) atof
(Standard C String and Character) atoi
(Standard C String and Character) atol
fprintf
printf


Standard C I/O::sscanf

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.


Standard C I/O::tmpfile

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


Standard C I/O::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


Standard C I/O::ungetc

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

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

Related topics:
getc
(C++ I/O) putback


Standard C I/O::vprintf, vfprintf, and vsprintf

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 (Other Standard C Functions) 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 Math

Display all entries for Standard C Math on one page, or view entries individually:

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

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;


Standard C Math::acos

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.


Standard C Math::asin

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.


Standard C Math::atan

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

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


Standard C Math::atan2

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.

Note the order of the arguments passed to this function.


Standard C Math::ceil

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.


Standard C Math::cos

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

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


Standard C Math::cosh

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

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


Standard C Math::div

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


Standard C Math::exp

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

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


Standard C Math::fabs

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

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


Standard C Math::floor

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.


Standard C Math::fmod

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

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


Standard C Math::frexp

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)


Standard C Math::labs

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

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


Standard C Math::ldexp

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.


Standard C Math::ldiv

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

Testing: adiv_t, div_t, ldiv_t.

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


Standard C Math::log

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.


Standard C Math::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


Standard C Math::modf

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.


Standard C Math::pow

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

The pow() function returns base raised to the expth 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 an overflow occurs.


Standard C Math::sin

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

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


Standard C Math::sinh

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

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


Standard C Math::sqrt

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.


Standard C Math::tan

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

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


Standard C Math::tanh

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

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


Standard C Memory

Display all entries for Standard C Memory on one page, or view entries individually:

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

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.


Standard C Memory::free

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
(C/C++ Keywords) delete
malloc
(C/C++ Keywords) new
realloc


Standard C Memory::malloc

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:
calloc
(C/C++ Keywords) delete
free
(C/C++ Keywords) new
realloc


Standard C Memory::realloc

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.


Standard C String and Character

Display all entries for Standard C String and Character on one page, or view entries individually:

atof | converts a string to a double
atoi | converts a string to an integer
atol | converts a string to a long
isalnum | true if a character is alphanumeric
isalpha | true if a character is alphabetic
iscntrl | true if a character is a control character
isdigit | true if a character is a digit
isgraph | true if a character is a graphical character
islower | true if a character is lowercase
isprint | true if a character is a printing character
ispunct | true if a character is punctuation
isspace | true if a character is a space character
isupper | true if a character is an uppercase character
isxdigit | true if a character is 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 and Character::atof

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
atol
(Standard C I/O) sprintf
strtod


Standard C String and Character::atoi

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.

You can use (Standard C I/O) sprintf() to convert a number into a string.

Related topics:
atof
atol
(Standard C I/O) sprintf


Standard C String and Character::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
atoi
(Standard C I/O) sprintf
strtol


Standard C String and Character::isalnum

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 );


Standard C String and Character::isalpha

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" );


Standard C String and Character::iscntrl

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.


Standard C String and Character::isdigit

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 );


Standard C String and Character::isgraph

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.


Standard C String and Character::islower

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


Standard C String and Character::isprint

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.


Standard C String and Character::ispunct

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.


Standard C String and Character::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.


Standard C String and Character::isupper

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.


Standard C String and Character::isxdigit

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.


Standard C String and Character::memchr

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" );


Standard C String and Character::memcmp

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


Standard C String and Character::memcpy

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. The return value of memcpy() is to. The behavior of memcpy() is undefined if to and from overlap.


Standard C String and Character::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.


Standard C String and Character::memset

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.


Standard C String and Character::strcat

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 );


Standard C String and Character::strchr

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.


Standard C String and Character::strcmp

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" );


Standard C String and Character::strcoll

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 (Standard C Date & Time) setlocale() function.

Related topics:
(Standard C Date & Time) setlocale
strcmp
strxfrm


Standard C String and Character::strcpy

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.


Standard C String and Character::strcspn

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.


Standard C String and Character::strerror

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

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


Standard C String and Character::strlen

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).


Standard C String and Character::strncat

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.


Standard C String and Character::strncmp

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.


Standard C String and Character::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.


Standard C String and Character::strpbrk

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 no such characters are present.

Related topics:
(C++ Algorithms) find_first_of
strchr
strcspn
strrchr
strspn
strstr
strtok


Standard C String and Character::strrchr

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.


Standard C String and Character::strspn

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.


Standard C String and Character::strstr

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.


Standard C String and Character::strtod

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


Standard C String and Character::strtok

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"


Standard C String and Character::strtol

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.


Standard C String and Character::strtoul

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


Standard C String and Character::strxfrm

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().


Standard C String and Character::tolower

tolower
Syntax:
  #include <ctype.h>

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


Standard C String and Character::toupper

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

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

Related topics:
tolower


All C Functions

cppreference.com > All C Functions
All C Functions
#, ## | manipulate 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 | used to undefine variables
Predefined preprocessor variables | miscellaneous preprocessor variables
abort | stops the program
abs | absolute value
acos | arc cosine
asctime | a textual version of the time
asin | arc sine
assert | stops the program if an expression isn't true
atan | arc tangent
atan2 | arc tangent, using signs to determine quadrants
atexit | sets a function to be called when the program exits
atof | converts a string to a double
atoi | converts a string to an integer
atol | converts a string to a long
bsearch | perform a binary search
calloc | allocates a two-dimensional chunk of memory
ceil | the smallest integer not less than a certain value
clearerr | clears errors
clock | returns the amount of time that the program has been running
cos | cosine
cosh | hyperbolic cosine
ctime | returns a specifically formatted version of the time
difftime | the difference between two times
div | returns the quotient and remainder of a division
exit | stop the program
exp | returns "e" raised to a given power
fabs | absolute value for floating-point numbers
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
floor | returns the largest integer not greater than a given value
fmod | returns the remainder of a division
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
free | makes memory available for future allocation
freopen | open an existing stream with a different name
frexp | decomposes a number into scientific notation
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
getenv | get enviornment information about a variable
gets | read a string from STDIN
gmtime | returns a pointer to the current Greenwich Mean Time
isalnum | true if a character is alphanumeric
isalpha | true if a character is alphabetic
iscntrl | true if a character is a control character
isdigit | true if a character is a digit
isgraph | true if a character is a graphical character
islower | true if a character is lowercase
isprint | true if a character is a printing character
ispunct | true if a character is punctuation
isspace | true if a character is a space character
isupper | true if a character is an uppercase character
isxdigit | true if a character is a hexidecimal character
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
localtime | returns a pointer to the current time
log | natural logarithm
log10 | natural logarithm, in base 10
longjmp | start execution at a certain point in the program
malloc | allocates memory
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
mktime | returns the calendar version of a given time
modf | decomposes a number into integer and fractional parts
perror | displays a string version of the current error to STDERR
pow | returns a given number raised to another number
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
qsort | perform a quicksort
raise | send a signal to the program
rand | returns a pseudorandom number
realloc | changes the size of previously allocated memory
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
setjmp | set execution to start at a certain point
setlocale | sets the current locale
setvbuf | set the buffer and size for a specific stream
signal | register a function as a signal handler
sin | sine
sinh | hyperbolic sine
sprintf | write formatted output to a buffer
sqrt | square root
srand | initialize the random number generator
sscanf | read formatted input from a buffer
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
strftime | returns individual elements of the date and time
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
system | perform a system call
tan | tangent
tanh | hyperbolic tangent
time | returns the current calendar time of the system
tmpfile | return a pointer to a temporary file
tmpnam | return a unique filename
tolower | converts a character to lowercase
toupper | converts a character to uppercase
ungetc | puts a character back into a stream
va_arg | use variable length parameter lists
vprintf, vfprintf, and vsprintf | write formatted output with variable argument lists


All C++ Functions

cppreference.com > All C++ Functions
All C++ Functions
Bitset Constructors (C++ Bitsets) | create new bitsets
Bitset Operators (C++ Bitsets) | compare and assign bitsets
Container constructors (C++ Vectors) | create containers and initialize them with some data
Container constructors (C++ Double-ended Queues) | create containers and initialize them with some data
Container constructors (C++ Lists) | create containers and initialize them with some data
Container constructors & destructors (C++ Sets) | default methods to allocate, copy, and deallocate containers
Container constructors & destructors (C++ Multisets) | default methods to allocate, copy, and deallocate containers
Container constructors & destructors (C++ Maps) | default methods to allocate, copy, and deallocate containers
Container constructors & destructors (C++ Multimaps) | default methods to allocate, copy, and deallocate containers
Container operators (C++ Lists) | assign and compare containers
Container operators (C++ Sets) | assign and compare containers
Container operators (C++ Multisets) | assign and compare containers
Container operators (C++ Multimaps) | assign and compare containers
Container operators (C++ Vectors) | compare, assign, and access elements of a container
Container operators (C++ Double-ended Queues) | compare, assign, and access elements of a container
I/O Constructors (C++ I/O) | constructors
Map operators (C++ Maps) | assign, compare, and access elements of a map
Priority queue constructors (C++ Priority Queues) | construct a new priority queue
Queue constructor (C++ Queues) | construct a new queue
Stack constructors (C++ Stacks) | construct a new stack
String constructors (C++ Strings) | create strings from arrays of characters and other strings
String operators (C++ Strings) | concatenate strings, assign strings, use strings for I/O, compare strings
any (C++ Bitsets) | true if any bits are set
append (C++ Strings) | append characters and strings onto a string
assign (C++ Vectors) | assign elements to a container
assign (C++ Double-ended Queues) | assign elements to a container
assign (C++ Lists) | assign elements to a container
assign (C++ Strings) | give a string values from strings of characters and other C++ strings
at (C++ Vectors) | returns an element at a specific location
at (C++ Double-ended Queues) | returns an element at a specific location
at (C++ Strings) | returns an element at a specific location
auto_ptr (Miscellaneous C++) | create pointers that automatically destroy objects
back (C++ Vectors) | returns a reference to last element of a container
back (C++ Double-ended Queues) | returns a reference to last element of a container
back (C++ Lists) | returns a reference to last element of a container
back (C++ Queues) | returns a reference to last element of a container
bad (C++ I/O) | true if an error occurred
begin (C++ Strings) | returns an iterator to the beginning of the container
begin (C++ Vectors) | returns an iterator to the beginning of the container
begin (C++ Double-ended Queues) | returns an iterator to the beginning of the container
begin (C++ Lists) | returns an iterator to the beginning of the container
begin (C++ Sets) | returns an iterator to the beginning of the container
begin (C++ Multisets) | returns an iterator to the beginning of the container
begin (C++ Maps) | returns an iterator to the beginning of the container
begin (C++ Multimaps) | returns an iterator to the beginning of the container
c_str (C++ Strings) | returns a standard C character array version of the string
capacity (C++ Vectors) | returns the number of elements that the container can hold
capacity (C++ Strings) | returns the number of elements that the container can hold
clear (C++ I/O) | clear status flags
clear (C++ Strings) | removes all elements from the container
clear (C++ Vectors) | removes all elements from the container
clear (C++ Double-ended Queues) | removes all elements from the container
clear (C++ Lists) | removes all elements from the container
clear (C++ Sets) | removes all elements from the container
clear (C++ Multisets) | removes all elements from the container
clear (C++ Maps) | removes all elements from the container
clear (C++ Multimaps) | removes all elements from the container
close (C++ I/O) | close a stream
compare (C++ Strings) | compares two strings
copy (C++ Strings) | copies characters from a string into an array
count (C++ Sets) | returns the number of elements matching a certain key
count (C++ Multisets) | returns the number of elements matching a certain key
count (C++ Maps) | returns the number of elements matching a certain key
count (C++ Multimaps) | returns the number of elements matching a certain key
count (C++ Bitsets) | returns the number of set bits
data (C++ Strings) | returns a pointer to the first character of a string
empty (C++ Strings) | true if the container has no elements
empty (C++ Vectors) | true if the container has no elements
empty (C++ Double-ended Queues) | true if the container has no elements
empty (C++ Lists) | true if the container has no elements
empty (C++ Sets) | true if the container has no elements
empty (C++ Multisets) | true if the container has no elements
empty (C++ Maps) | true if the container has no elements
empty (C++ Multimaps) | true if the container has no elements
empty (C++ Stacks) | true if the container has no elements
empty (C++ Queues) | true if the container has no elements
empty (C++ Priority Queues) | true if the container has no elements
end (C++ Strings) | returns an iterator just past the last element of a container
end (C++ Vectors) | returns an iterator just past the last element of a container
end (C++ Double-ended Queues) | returns an iterator just past the last element of a container
end (C++ Lists) | returns an iterator just past the last element of a container
end (C++ Sets) | returns an iterator just past the last element of a container
end (C++ Multisets) | returns an iterator just past the last element of a container
end (C++ Maps) | returns an iterator just past the last element of a container
end (C++ Multimaps) | returns an iterator just past the last element of a container
eof (C++ I/O) | true if at the end-of-file
equal_range (C++ Sets) | returns iterators to the first and just past the last elements matching a specific key
equal_range (C++ Multisets) | returns iterators to the first and just past the last elements matching a specific key
equal_range (C++ Maps) | returns iterators to the first and just past the last elements matching a specific key
equal_range (C++ Multimaps) | returns iterators to the first and just past the last elements matching a specific key
erase (C++ Strings) | removes elements from a string
erase (C++ Vectors) | removes elements from a container
erase (C++ Double-ended Queues) | removes elements from a container
erase (C++ Lists) | removes elements from a container
erase (C++ Sets) | removes elements from a container
erase (C++ Multisets) | removes elements from a container
erase (C++ Maps) | removes elements from a container
erase (C++ Multimaps) | removes elements from a container
fail (C++ I/O) | true if an error occurred
fill (C++ I/O) | manipulate the default fill character
find (C++ Sets) | returns an iterator to specific elements
find (C++ Multisets) | returns an iterator to specific elements
find (C++ Maps) | returns an iterator to specific elements
find (C++ Multimaps) | returns an iterator to specific elements
find (C++ Strings) | find characters in the string
find_first_not_of (C++ Strings) | find first absence of characters
find_first_of (C++ Strings) | find first occurrence of characters
find_last_not_of (C++ Strings) | find last absence of characters
find_last_of (C++ Strings) | find last occurrence of characters
flags (C++ I/O) | access or manipulate io stream format flags
flip (C++ Bitsets) | reverses the bitset
flush (C++ I/O) | empty the buffer
front (C++ Vectors) | returns a reference to the first element of a container
front (C++ Double-ended Queues) | returns a reference to the first element of a container
front (C++ Lists) | returns a reference to the first element of a container
front (C++ Queues) | returns a reference to the first element of a container
gcount (C++ I/O) | number of characters read during last input
get (C++ I/O) | read characters
getline (C++ I/O) | read a line of characters
getline (C++ Strings) | read data from an I/O stream into a string
good (C++ I/O) | true if no errors have occurred
ignore (C++ I/O) | read and discard characters
insert (C++ Strings) | insert characters into a string
insert (C++ Vectors) | inserts elements into the container
insert (C++ Double-ended Queues) | inserts elements into the container
insert (C++ Lists) | inserts elements into the container
insert (C++ Sets) | insert items into a container
insert (C++ Multisets) | inserts items into a container
insert (C++ Multimaps) | inserts items into a container
insert (C++ Maps) | insert items into a container
key_comp (C++ Sets) | returns the function that compares keys
key_comp (C++ Multisets) | returns the function that compares keys
key_comp (C++ Maps) | returns the function that compares keys
key_comp (C++ Multimaps) | returns the function that compares keys
length (C++ Strings) | returns the length of the string
lower_bound (C++ Sets) | returns an iterator to the first element greater than or equal to a certian value
lower_bound (C++ Multisets) | returns an iterator to the first element greater than or equal to a certian value
lower_bound (C++ Maps) | returns an iterator to the first element greater than or equal to a certian value
lower_bound (C++ Multimaps) | returns an iterator to the first element greater than or equal to a certian value
max_size (C++ Strings) | returns the maximum number of elements that the container can hold
max_size (C++ Vectors) | returns the maximum number of elements that the container can hold
max_size (C++ Double-ended Queues) | returns the maximum number of elements that the container can hold
max_size (C++ Lists) | returns the maximum number of elements that the container can hold
max_size (C++ Sets) | returns the maximum number of elements that the container can hold
max_size (C++ Multisets) | returns the maximum number of elements that the container can hold
max_size (C++ Maps) | returns the maximum number of elements that the container can hold
max_size (C++ Multimaps) | returns the maximum number of elements that the container can hold
merge (C++ Lists) | merge two lists
none (C++ Bitsets) | true if no bits are set
open (C++ I/O) | create an input stream
peek (C++ I/O) | check the next input character
pop (C++ Stacks) | removes the top element of a container
pop (C++ Queues) | removes the top element of a container
pop (C++ Priority Queues) | removes the top element of a container
pop_back (C++ Vectors) | removes the last element of a container
pop_back (C++ Double-ended Queues) | removes the last element of a container
pop_back (C++ Lists) | removes the last element of a container
pop_front (C++ Double-ended Queues) | removes the first element of the container
pop_front (C++ Lists) | removes the first element of the container
precision (C++ I/O) | manipulate the precision of a stream
push (C++ Stacks) | adds an element to the top of the container
push (C++ Queues) | adds an element to the end of the container
push (C++ Priority Queues) | adds an element to the end of the container
push_back (C++ Vectors) | add an element to the end of the container
push_back (C++ Double-ended Queues) | add an element to the end of the container
push_back (C++ Lists) | add an element to the end of the container
push_back (C++ Strings) | add an element to the end of the container
push_front (C++ Double-ended Queues) | add an element to the front of the container
push_front (C++ Lists) | add an element to the front of the container
put (C++ I/O) | write characters
putback (C++ I/O) | return characters to a stream
rbegin (C++ Vectors) | returns a reverse_iterator to the end of the container
rbegin (C++ Strings) | returns a reverse_iterator to the end of the container
rbegin (C++ Double-ended Queues) | returns a reverse_iterator to the end of the container
rbegin (C++ Lists) | returns a reverse_iterator to the end of the container
rbegin (C++ Sets) | returns a reverse_iterator to the end of the container
rbegin (C++ Multisets) | returns a reverse_iterator to the end of the container
rbegin (C++ Maps) | returns a reverse_iterator to the end of the container
rbegin (C++ Multimaps) | returns a reverse_iterator to the end of the container
rdstate (C++ I/O) | returns the state flags of the stream
read (C++ I/O) | read data into a buffer
remove (C++ Lists) | removes elements from a list
remove_if (C++ Lists) | removes elements conditionally
rend (C++ Vectors) | returns a reverse_iterator to the beginning of the container
rend (C++ Strings) | returns a reverse_iterator to the beginning of the container
rend (C++ Double-ended Queues) | returns a reverse_iterator to the beginning of the container
rend (C++ Lists) | returns a reverse_iterator to the beginning of the container
rend (C++ Sets) | returns a reverse_iterator to the beginning of the container
rend (C++ Multisets) | returns a reverse_iterator to the beginning of the container
rend (C++ Maps) | returns a reverse_iterator to the beginning of the container
rend (C++ Multimaps) | returns a reverse_iterator to the beginning of the container
replace (C++ Strings) | replace characters in the string
reserve (C++ Vectors) | sets the minimum capacity of the container
reserve (C++ Strings) | sets the minimum capacity of the container
reset (C++ Bitsets) | sets bits to zero
resize (C++ Vectors) | change the size of the container
resize (C++ Double-ended Queues) | change the size of the container
resize (C++ Lists) | change the size of the container
resize (C++ Strings) | change the size of the container
reverse (C++ Lists) | reverse the list
rfind (C++ Strings) | find the last occurrence of a substring
seekg (C++ I/O) | perform random access on an input stream
seekp (C++ I/O) | perform random access on output streams
set (C++ Bitsets) | sets bits
setf (C++ I/O) | set format flags
size (C++ Strings) | returns the number of items in the container
size (C++ Vectors) | returns the number of items in the container
size (C++ Double-ended Queues) | returns the number of items in the container
size (C++ Lists) | returns the number of items in the container
size (C++ Sets) | returns the number of items in the container
size (C++ Multisets) | returns the number of items in the container
size (C++ Maps) | returns the number of items in the container
size (C++ Multimaps) | returns the number of items in the container
size (C++ Stacks) | returns the number of items in the container
size (C++ Queues) | returns the number of items in the container
size (C++ Priority Queues) | returns the number of items in the container
size (C++ Bitsets) | number of bits that the bitset can hold
sort (C++ Lists) | sorts the list
splice (C++ Lists) | merge two lists in constant time
substr (C++ Strings) | returns a certain substring
swap (C++ Strings) | swap the contents of this container with another
swap (C++ Vectors) | swap the contents of this container with another
swap (C++ Double-ended Queues) | swap the contents of this container with another
swap (C++ Lists) | swap the contents of this container with another
swap (C++ Sets) | swap the contents of this container with another
swap (C++ Multisets) | swap the contents of this container with another
swap (C++ Maps) | swap the contents of this container with another
swap (C++ Multimaps) | swap the contents of this container with another
sync_with_stdio (C++ I/O) | synchronize with standard I/O
tellg (C++ I/O) | read input stream pointers
tellp (C++ I/O) | read output stream pointers
test (C++ Bitsets) | returns the value of a given bit
to_string (C++ Bitsets) | string representation of the bitset
to_ulong (C++ Bitsets) | returns an integer representation of the bitset
top (C++ Stacks) | returns the top element of the container
top (C++ Priority Queues) | returns the top element of the container
unique (C++ Lists) | removes duplicate elements
unsetf (C++ I/O) | clear io stream format flags
upper_bound (C++ Sets) | returns an iterator to the first element greater than a certain value
upper_bound (C++ Multisets) | returns an iterator to the first element greater than a certain value
upper_bound (C++ Maps) | returns an iterator to the first element greater than a certain value
upper_bound (C++ Multimaps) | returns an iterator to the first element greater than a certain value
value_comp (C++ Sets) | returns the function that compares values
value_comp (C++ Multisets) | returns the function that compares values
value_comp (C++ Maps) | returns the function that compares values
value_comp (C++ Multimaps) | returns the function that compares values
width (C++ I/O) | access and manipulate the minimum field width
write (C++ I/O) | write characters


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


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. Similarily, when referring to containers associated with pairs of data (map for example) key_type and value_type are used to refer to the key and value types for that container.


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.


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:

A.J.M. van den Berg - Adrian Pfisterer - Alex Vinokur - Alex Wilson - Alexandre Kostine - Andre - Andrew L Roth - Brian Higgins - Carl - Cedric Blaser - Chris H - Chris Rimmer - Chris Yate - Christoph Vogelbusch - Damian (doublenegative) - Daniel Lorch - Darsh Ranjan - Dave Schuyler - Dave T - Deepak Goyal - Drew Dormann - Dzu Nguyen - Edgardo Rossetto - Emmanuel Viaud - Fred Ma - Gerhard Grossauer - Guillaume Bouchez - Henrik Huttunen - Iain Staffell - JP (Pete) Donnell - Jari Karppinen - Jeff Bowden - Jeroen Missinne - Jonathan Kleid - Joseph Bruni - Justin M. Lee - Katherine Haines - Kuang-che Wu - Kurt McKee - Leor Zolman - Lucas Fisher - Mael Herz - Magnus Kulke - Manish Malik - Martin - Martijn van de Giessen - Mike Ekoka - Mike Jennings - Milan Mimica - Nick Gianakas - Nicolas Boichat - Olivier Ricou - Onur Tugcu - Osku Salerma - Paul L. Tomlinson - Philip Dunstan - Phillip Lee - Piers Daniell - Roger D Pack - Salman Mahbub - Sergio Martinez - Shibukawa Yoshiki - Stefan Suffa - Thomas Volk - Tiaan van Aardt - Tom (prkchp) - Vegard Nossum - Vijay S. - Wouter Lievens - XenteX

Thank you!


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.


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?"


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.


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

All C Functions

C++

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

C++ Standard Template Library

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

All C++ Functions

Questions? Check out the FAQ, look at these other language references, or contact us.

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


I/O Flags

cppreference.com > I/O Flags

C++ I/O Flags

Format 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.

Manipulators

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

State flags

The I/O stream state flags tell you the current state of an I/O stream. The flags are:

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

Mode flags

The I/O stream mode flags allow you to access files in different ways. The flags are:

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


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.


Links

Here are some links to other language references:

  • C++ (Dinkumware)
  • C++ Language and Library
  • Java 1.5 (Sun)
  • MySQL
  • Perl
  • Python
  • Ruby
  • Visual C++ STL (Microsoft)


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 | ,


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.


C++ Bitsets
Bitset 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;

Bitset 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.

Related topics:
count
none
count
Syntax:
  size_type count();

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

Related topics:
any
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.

none
Syntax:
  bool none();

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

Related topics:
any
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.

Related topics:
to_ulong
to_ulong
Syntax:
  unsigned long to_ulong();

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

Related topics:
to_string


C++ Double-ended Queues
swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current dequeue with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice
begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the dequeue. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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
rbegin
rend
end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the dequeue.

Note that before you can access the last element of the dequeue using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.

Related topics:
begin
rbegin
rend
rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current dequeue.

rbegin() runs in constant time.

Related topics:
begin
end
rend
rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current dequeue.

rend() runs in constant time.

Related topics:
begin
end
rbegin
size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
resize
max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size
empty
Syntax:
  bool empty() const;

The empty() function returns true if the dequeue has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a dequeue and display 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
clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the dequeue. clear() runs in linear time.

Related topics:
erase
Container constructors
Syntax:
  container();
  container( const container& c );
  container( size_type num, const TYPE& val = TYPE() );
  container( input_iterator start, input_iterator end );
  ~container();

The default dequeue constructor takes no arguments, creates a new instance of that dequeue.

The second constructor is a default copy constructor that can be used to create a new dequeue that is a copy of the given dequeue c.

The third constructor creates a dequeue with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a vector consisting of five copies of the integer 42:

 vector<int> v1( 5, 42 );

The last constructor creates a dequeue that is initialized to contain the elements between start and end. For example:

 // create a vector of random integers
 cout << "original vector: ";
 vector<int> v;
 for( int i = 0; i < 10; i++ ) {
   int num = (int) rand() % 10;
   cout << num << " ";
   v.push_back( num );
 }
 cout << endl;
 // find the first element of v that is even
 vector<int>::iterator iter1 = v.begin();
 while( iter1 != v.end() && *iter1 % 2 != 0 ) {
   iter1++;
 }
 // find the last element of v that is even
 vector<int>::iterator iter2 = v.end();
 do {
   iter2--;
 } while( iter2 != v.begin() && *iter2 % 2 != 0 );
 cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;
 cout << "new vector: ";
 vector<int> v2( iter1, iter2 );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, this code displays the following output:

 original vector: 1 9 7 9 2 7 2 1 9 8
 first even number: 2, last even number: 8
 new vector: 2 7 2 1 9

All of these constructors run in linear time except the first, which runs in constant time.

The default destructor is called when the dequeue should be destroyed.

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

The assign() function either gives the current dequeue the values from start to end, or gives it num copies of val.

This function will destroy the previous contents of the dequeue.

For example, the following code uses assign() to put 10 copies of the integer 42 into a vector:

 vector<int> v;
 v.assign( 10, 42 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << v[i] << " ";
 }
 cout << endl;

The above code displays the following output:

 42 42 42 42 42 42 42 42 42 42

The next example shows how assign() can be used to copy one vector to another:

 vector<int> v1;
 for( int i = 0; i < 10; i++ ) {
   v1.push_back( i );
 }
 vector<int> v2;
 v2.assign( v1.begin(), v1.end() );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, the above code displays the following output:

 0 1 2 3 4 5 6 7 8 9

Related topics:
(C++ Strings) assign
insert
push_back
push_front
resize
Syntax:
  void resize( size_type num, const TYPE& val = TYPE() );

The function resize() changes the size of the dequeue to size. If val is specified then any newly-created elements will be initialized to have a value of val.

This function runs in linear time.

Related topics:
(C++ Multimaps) Container constructors & destructors
(C++ Strings) capacity
size
insert
Syntax:
  iterator insert( iterator loc, const TYPE& val );
  void insert( iterator loc, size_type num, const TYPE& val );
  template<TYPE> void insert( iterator loc, input_iterator start, input_iterator end );

The insert() function either:

  • inserts val before loc, returning an iterator to the element inserted,
  • 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

Related topics:
assign
erase
(C++ Lists) merge
push_back
push_front
(C++ Lists) splice
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.

The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, dequeues, and strings. The multiple-element version of erase always takes linear time.

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

In the next example, erase() is called with two iterators to delete a range of elements from a vector:

 // 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 );
 }
 // display the complete vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;
 // use erase to remove all but the first two and last three elements
 // of the vector
 alphaVector.erase( alphaVector.begin()+2, alphaVector.end()-3 );
 // display the modified vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;

When run, the above code displays:

 ABCDEFGHIJ
 ABHIJ

Related topics:
clear
insert
pop_back
pop_front
(C++ Lists) remove
(C++ Lists) remove_if
front
Syntax:
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the dequeue, and runs in constant time.

Related topics:
back
pop_front
push_front
back
Syntax:
  TYPE& back();
  const TYPE& back() const;

The back() function returns a reference to the last element in the dequeue.

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

The back() function runs in constant time.

Related topics:
front
pop_back
push_front
Syntax:
  void push_front( const TYPE& val );

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

push_front() runs in constant time.

Related topics:
assign
front
insert
pop_front
push_back
push_back
Syntax:
  void push_back( const TYPE& val );

The push_back() function appends val to the end of the dequeue.

For example, the following code puts 10 integers into a list:

   list<int> the_list;
   for( int i = 0; i < 10; i++ )
     the_list.push_back( i );

When displayed, the resulting list would look like this:

 0 1 2 3 4 5 6 7 8 9

push_back() runs in constant time.

Related topics:
assign
insert
pop_back
push_front
pop_front
Syntax:
  void pop_front();

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

The pop_front() function runs in constant time.

Related topics:
erase
front
pop_back
push_front
pop_back
Syntax:
  void pop_back();

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

pop_back() runs in constant time.

Related topics:
back
erase
pop_front
push_back
Container operators
Syntax:
  TYPE& operator[]( size_type index );
  const TYPE& operator[]( size_type index ) const;
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Individual elements of a dequeue can be examined with the [] operator.

Performing a comparison or assigning one dequeue to another takes linear time. The [] operator runs in constant time.

Two `containers` are equal if:

  1. Their size is the same, and
  2. Each member in location i in one dequeue is equal to the the member in location i in the other dequeue.

Comparisons among dequeues are done lexicographically.

For example, the following code uses the [] operator to access all of the elements of a vector:

 vector<int> v( 5, 1 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << "Element " << i << " is " << v[i] << endl;
 }

Related topics:
at
at
Syntax:
  TYPE& at( size_type loc );
  const TYPE& at( size_type loc ) const;

The at() function returns a reference to the element in the dequeue at index loc. The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the dequeue.

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:
(C++ Multimaps) Container operators
Container operators


C++ I/O
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:
eof
fail
good
rdstate
clear
Syntax:
  void clear( iostate flags = ios::goodbit );

The function clear() clears the io stream state flags associated with the current stream. The flags argument defaults to ios::goodbit, which means that all flags will be cleared. Otherwise, only the flags specified by flags are cleared.

Related topics:
eof
fail
good
rdstate
close
Syntax:
  void close();

The close() function closes the associated file stream.

Related topics:
I/O Constructors
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, the following code reads data from an input stream in and writes it to an output stream out, using eof() at the end to check if an error occurred:

 char buf[BUFSIZE];
 do {
   in.read( buf, BUFSIZE );
   std::streamsize n = in.gcount();
   out.write( buf, n );
 } while( in.good() );
 if( in.bad() || !in.eof() ) {
   // fatal error occurred
 }
 in.close();

Related topics:
bad
clear
fail
good
rdstate
fail
Syntax:
  bool fail();

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

Related topics:
bad
clear
eof
good
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 io stream format flags for the current stream, or sets the flags for the current stream to be f.

Related topics:
setf
unsetf
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 a file called temp.txt, character by character:

   char ch;
   ifstream fin( "temp.txt" );
   while( fin.get(ch) )
     cout << ch;
   fin.close();

Related topics:
gcount
getline
(C++ Strings) getline
ignore
peek
put
read
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.

Those using a Microsoft compiler may find that getline() reads an extra character, and should consult the documentation on the Microsoft getline bug.

Related topics:
gcount
get
(C++ Strings) getline
ignore
read
good
Syntax:
  bool good();

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

Related topics:
bad
clear
eof
fail
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 (where num defaults to 1) or until the character delim is read (where delim defaults to EOF).

Related topics:
get
getline
open
Syntax:
  void open( const char *filename );
  void open( const char *filename, openmode mode = default_mode );

The function open() is used with file streams. It opens filename and associates it with the current stream. The optional io stream mode flag mode defaults to ios::in for ifstream, ios::out for ofstream, and ios::in|ios::out for fstream.

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:
I/O Constructors
close
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 sets the precision of the cout stream to 5:

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

This code displays the following output:

   314.16

Related topics:
fill
width
put
Syntax:
  ostream &put( char ch );

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

Related topics:
flush
get
write
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
(Standard C I/O) ungetc
rdstate
Syntax:
  iostate rdstate();

The rdstate() function returns the io stream state flags of the current stream.

Related topics:
bad
clear
eof
fail
good
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 io stream format flags of the current stream to flags. The optional needed argument specifies that only the flags that are in both flags and needed should be set. The return value is the previous configuration of io stream format 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 io stream 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() uses flags to clear the io stream format flags associated with the current stream.

Related topics:
flags
setf
width
Syntax:
  int width();
  int width( int w );

The function width() returns the current width, which is defined as the minimum number of characters to display with each output. The optional argument w can be used to set the width.

For example:

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

displays

       2

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

Related topics:
fill
precision
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.


C++ Lists
swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current list with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
splice
Container operators
Syntax:
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one list to another takes linear time.

Two lists are equal if:

  1. Their size is the same, and
  2. Each member in location i in one list is equal to the the member in location i in the other list.

Comparisons among lists are done lexicographically.

Related topics:
(C++ Strings) String operators
(C++ Strings) at
merge
unique
begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the list. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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
rbegin
rend
end
Syntax:
  iterator end();
  const_iterator end() const;

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

Note that before you can access the last element of the list using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.

Related topics:
begin
rbegin
rend
rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current list.

rbegin() runs in constant time.

Related topics:
begin
end
rend
rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current list.

rend() runs in constant time.

Related topics:
begin
end
rbegin
size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
resize
max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size
empty
Syntax:
  bool empty() const;

The empty() function returns true if the list has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a list and display 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
clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the list. clear() runs in linear time.

Related topics:
erase
Container constructors
Syntax:
  container();
  container( const container& c );
  container( size_type num, const TYPE& val = TYPE() );
  container( input_iterator start, input_iterator end );
  ~container();

The default list constructor takes no arguments, creates a new instance of that list.

The second constructor is a default copy constructor that can be used to create a new list that is a copy of the given list c.

The third constructor creates a list with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a vector consisting of five copies of the integer 42:

 vector<int> v1( 5, 42 );

The last constructor creates a list that is initialized to contain the elements between start and end. For example:

 // create a vector of random integers
 cout << "original vector: ";
 vector<int> v;
 for( int i = 0; i < 10; i++ ) {
   int num = (int) rand() % 10;
   cout << num << " ";
   v.push_back( num );
 }
 cout << endl;
 // find the first element of v that is even
 vector<int>::iterator iter1 = v.begin();
 while( iter1 != v.end() && *iter1 % 2 != 0 ) {
   iter1++;
 }
 // find the last element of v that is even
 vector<int>::iterator iter2 = v.end();
 do {
   iter2--;
 } while( iter2 != v.begin() && *iter2 % 2 != 0 );
 cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;
 cout << "new vector: ";
 vector<int> v2( iter1, iter2 );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, this code displays the following output:

 original vector: 1 9 7 9 2 7 2 1 9 8
 first even number: 2, last even number: 8
 new vector: 2 7 2 1 9

All of these constructors run in linear time except the first, which runs in constant time.

The default destructor is called when the list should be destroyed.

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

The assign() function either gives the current list the values from start to end, or gives it num copies of val.

This function will destroy the previous contents of the list.

For example, the following code uses assign() to put 10 copies of the integer 42 into a vector:

 vector<int> v;
 v.assign( 10, 42 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << v[i] << " ";
 }
 cout << endl;

The above code displays the following output:

 42 42 42 42 42 42 42 42 42 42

The next example shows how assign() can be used to copy one vector to another:

 vector<int> v1;
 for( int i = 0; i < 10; i++ ) {
   v1.push_back( i );
 }
 vector<int> v2;
 v2.assign( v1.begin(), v1.end() );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, the above code displays the following output:

 0 1 2 3 4 5 6 7 8 9

Related topics:
(C++ Strings) assign
insert
push_back
push_front
resize
Syntax:
  void resize( size_type num, const TYPE& val = TYPE() );

The function resize() changes the size of the list to size. If val is specified then any newly-created elements will be initialized to have a value of val.

This function runs in linear time.

Related topics:
(C++ Multimaps) Container constructors & destructors
(C++ Strings) capacity
size
insert
Syntax:
  iterator insert( iterator loc, const TYPE& val );
  void insert( iterator loc, size_type num, const TYPE& val );
  template<TYPE> void insert( iterator loc, input_iterator start, input_iterator end );

The insert() function either:

  • inserts val before loc, returning an iterator to the element inserted,
  • 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

Related topics:
assign
erase
merge
push_back
push_front
splice
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.

The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, dequeues, and strings. The multiple-element version of erase always takes linear time.

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

In the next example, erase() is called with two iterators to delete a range of elements from a vector:

 // 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 );
 }
 // display the complete vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;
 // use erase to remove all but the first two and last three elements
 // of the vector
 alphaVector.erase( alphaVector.begin()+2, alphaVector.end()-3 );
 // display the modified vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;

When run, the above code displays:

 ABCDEFGHIJ
 ABHIJ

Related topics:
clear
insert
pop_back
pop_front
remove
remove_if
front
Syntax:
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the list, and runs in constant time.

Related topics:
back
pop_front
push_front
back
Syntax:
  TYPE& back();
  const TYPE& back() const;

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

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

The back() function runs in constant time.

Related topics:
front
pop_back
push_front
Syntax:
  void push_front( const TYPE& val );

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

push_front() runs in constant time.

Related topics:
assign
front
insert
pop_front
push_back
push_back
Syntax:
  void push_back( const TYPE& val );

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

For example, the following code puts 10 integers into a list:

   list<int> the_list;
   for( int i = 0; i < 10; i++ )
     the_list.push_back( i );

When displayed, the resulting list would look like this:

 0 1 2 3 4 5 6 7 8 9

push_back() runs in constant time.

Related topics:
assign
insert
pop_back
push_front
pop_front
Syntax:
  void pop_front();

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

The pop_front() function runs in constant time.

Related topics:
erase
front
pop_back
push_front
pop_back
Syntax:
  void pop_back();

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

pop_back() runs in constant time.

Related topics:
back
erase
pop_front
push_back
splice
Syntax:
  void splice( iterator pos, list& lst );
  void splice( iterator pos, list& lst, iterator del );
  void splice( iterator pos, list& 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.

splice() simply moves elements from one list to another, and doesn't actually do any copying or deleting. Because of this, splice() runs in constant time.

Related topics:
insert
merge
swap
remove
Syntax:
  void remove( const TYPE &val );

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

For example, the following code creates a list of the first 10 characters of the alphabet, then uses remove() to remove the letter 'E' from the list:

   // 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 runs in linear time.

Related topics:
erase
remove_if
unique
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.

remove_if() runs in linear time.

Related topics:
erase
remove
unique
unique
Syntax:
  void unique();
  void unique( BinPred pr );

The function unique() removes all duplicate elements from the list. Equality is tested using the == operator, unless pr is specified as a replacement. The ordering of the elements in a list should not change after a call to unique().

unique() runs in linear time.

Related topics:
Container operators
remove
remove_if
sort
Syntax:
  void sort();
  void sort( BinPred compfunction );

The sort() function is used to sort lists. Ordering is done via the < operator, unless compfunction is specified, in which case it is used to determine if an element is less than another.

Sorting takes n * log(n) time.

Related topics:
reverse
merge
Syntax:
  void merge( list &lst );
  void merge( list &lst, BinPred compfunction );

The function merge() merges the list with lst, producing a combined list that is ordered with respect to the < operator. If compfunction is specified, then it is used as the comparison function for the lists instead of <.

merge() runs in linear time.

Related topics:
Container operators
insert
splice
reverse
Syntax:
  void reverse();

The function reverse() reverses the list, and takes linear time.

Related topics:
sort


C++ Maps
swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current map with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice
begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the map. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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
rbegin
rend
end
Syntax:
  iterator end();
  const_iterator end() const;

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

Note that before you can access the last element of the map using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.

Related topics:
begin
rbegin
rend
rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current map.

rbegin() runs in constant time.

Related topics:
begin
end
rend
rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current map.

rend() runs in constant time.

Related topics:
begin
end
rbegin
size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
(C++ Strings) resize
max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size
empty
Syntax:
  bool empty() const;

The empty() function returns true if the map has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a map and display 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
clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the map. clear() runs in linear time.

Related topics:
(C++ Lists) erase
Container constructors & destructors
Syntax:
  container();
  container( const container& c );
  ~container();

Every map has a default constructor, copy constructor, and destructor.

The default constructor takes no arguments, creates a new instance of that map, and runs in constant time. The default copy constructor runs in linear time and can be used to create a new map that is a copy of the given map c.

The default destructor is called when the map should be destroyed.

For example, the following code creates a pointer to a vector of integers and then uses the default map constructor to allocate a memory for a new vector:

 vector<int>* v;
 v = new vector<int>();

Related topics:
(C++ Strings) resize
key_comp
Syntax:
  key_compare key_comp() const;

The function key_comp() returns the function that compares keys.

key_comp() runs in constant time.

Related topics:
value_comp
value_comp
Syntax:
  value_compare value_comp() const;

The value_comp() function returns the function that compares values.

value_comp() runs in constant time.

Related topics:
key_comp
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 pos (where pos is really just a suggestion as to where val should go, since sets and maps are ordered), 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.

Related topics:
Map operators
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.

find() runs in logarithmic time.

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.

lower_bound() runs in logarithmic time.

Related topics:
upper_bound
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.

Related topics:
lower_bound
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 a point just after 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.

Map operators
Syntax:
  TYPE& operator[]( const key_type& key );
  map operator=(const map& c2);
  bool operator==(const map& c1, const map& c2);
  bool operator!=(const map& c1, const map& c2);
  bool operator<(const map& c1, const map& c2);
  bool operator>(const map& c1, const map& c2);
  bool operator<=(const map& c1, const map& c2);
  bool operator>=(const map& c1, const map& c2);

Maps can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Individual elements of a map can be examined with the [] operator.

Performing a comparison or assigning one map to another takes linear time.

Two maps are equal if:

  1. Their size is the same, and
  2. Each member in location i in one map is equal to the the member in location i in the other map.

Comparisons among maps are done lexicographically.

Related topics:
insert
count
Syntax:
  size_type count( const key_type& key );

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

count() should run in logarithmic time.


Miscellaneous C++
auto_ptr
Syntax:
  #include<memory>
  auto_ptr<class TYPE> name

The auto_ptr class allows the programmer to create pointers that point to other objects. When auto_ptr pointers are destroyed, the objects to which they point are also destroyed. The auto_ptr class supports normal pointer operations like =, *, and ->, as well as two functions TYPE* get() and TYPE* release(). The get() function returns a pointer to the object that the auto_ptr points to. The release() function acts similarily to the get() function, but also relieves the auto_ptr of its memory destruction duties. When an auto_ptr that has been released goes out of scope, it will not call the destructor of the object that it points to.

 #include <memory>
 using namespace std;
 class MyClass {
 public:
   MyClass() { // nothing }
   ~MyClass() { // nothing }
   void myFunc() { // nothing }
 };
 int main() {
   auto_ptr<MyClass> ptr1(new MyClass), ptr2;
   ptr2 = ptr1;
   ptr2->myFunc();
   MyClass* ptr = ptr2.get();
   ptr->myFunc();
   return 0;
 }


C++ Multimaps
swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current multimap with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice
Container operators
Syntax:
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one multimap to another takes linear time.

Two multimaps are equal if:

  1. Their size is the same, and
  2. Each member in location i in one multimap is equal to the the member in location i in the other multimap.

Comparisons among multimaps are done lexicographically.

Related topics:
(C++ Strings) String operators
(C++ Strings) at
(C++ Lists) merge
(C++ Lists) unique
begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the multimap. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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
rbegin
rend
end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the multimap.

Note that before you can access the last element of the multimap using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.

Related topics:
begin
rbegin
rend
rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current multimap.

rbegin() runs in constant time.

Related topics:
begin
end
rend
rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current multimap.

rend() runs in constant time.

Related topics:
begin
end
rbegin
size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
(C++ Strings) resize
max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size
empty
Syntax:
  bool empty() const;

The empty() function returns true if the multimap has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a multimap and display 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
clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the multimap. clear() runs in linear time.

Related topics:
(C++ Lists) erase
Container constructors & destructors
Syntax:
  container();
  container( const container& c );
  ~container();

Every multimap has a default constructor, copy constructor, and destructor.

The default constructor takes no arguments, creates a new instance of that multimap, and runs in constant time. The default copy constructor runs in linear time and can be used to create a new multimap that is a copy of the given multimap c.

The default destructor is called when the multimap should be destroyed.

For example, the following code creates a pointer to a vector of integers and then uses the default multimap constructor to allocate a memory for a new vector:

 vector<int>* v;
 v = new vector<int>();

Related topics:
(C++ Strings) resize
key_comp
Syntax:
  key_compare key_comp() const;

The function key_comp() returns the function that compares keys.

key_comp() runs in constant time.

Related topics:
value_comp
value_comp
Syntax:
  value_compare value_comp() const;

The value_comp() function returns the function that compares values.

value_comp() runs in constant time.

Related topics:
key_comp
insert
Syntax:
  iterator insert( iterator i, const TYPE& val );
  void insert( input_iterator start, input_iterator end );
  iterator insert( const TYPE& val );

The function insert() either:
  • inserts val after the element at pos (where pos is really just a suggestion as to where val should go, since multisets and multimaps are ordered), and returns an iterator to that element.
  • inserts a range of elements from start to end.
  • inserts val into the multimap. The return value is an iterator to the element inserted, and a boolean describing whether an insertion took place.

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.

find() runs in logarithmic time.

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.

lower_bound() runs in logarithmic time.

Related topics:
upper_bound
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.

Related topics:
lower_bound
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 a point just after 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.

count
Syntax:
  size_type count( const key_type& key );

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

count() should run in logarithmic time.


C++ Multisets
swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current multiset with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice
Container operators
Syntax:
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one multiset to another takes linear time.

Two multisets are equal if:

  1. Their size is the same, and
  2. Each member in location i in one multiset is equal to the the member in location i in the other multiset.

Comparisons among multisets are done lexicographically.

Related topics:
(C++ Strings) String operators
(C++ Strings) at
(C++ Lists) merge
(C++ Lists) unique
begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the multiset. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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
rbegin
rend
end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the multiset.

Note that before you can access the last element of the multiset using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.

Related topics:
begin
rbegin
rend
rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current multiset.

rbegin() runs in constant time.

Related topics:
begin
end
rend
rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current multiset.

rend() runs in constant time.

Related topics:
begin
end
rbegin
size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
(C++ Strings) resize
max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size
empty
Syntax:
  bool empty() const;

The empty() function returns true if the multiset has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a multiset and display 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
clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the multiset. clear() runs in linear time.

Related topics:
(C++ Lists) erase
Container constructors & destructors
Syntax:
  container();
  container( const container& c );
  ~container();

Every multiset has a default constructor, copy constructor, and destructor.

The default constructor takes no arguments, creates a new instance of that multiset, and runs in constant time. The default copy constructor runs in linear time and can be used to create a new multiset that is a copy of the given multiset c.

The default destructor is called when the multiset should be destroyed.

For example, the following code creates a pointer to a vector of integers and then uses the default multiset constructor to allocate a memory for a new vector:

 vector<int>* v;
 v = new vector<int>();

Related topics:
(C++ Strings) resize
key_comp
Syntax:
  key_compare key_comp() const;

The function key_comp() returns the function that compares keys.

key_comp() runs in constant time.

Related topics:
value_comp
value_comp
Syntax:
  value_compare value_comp() const;

The value_comp() function returns the function that compares values.

value_comp() runs in constant time.

Related topics:
key_comp
insert
Syntax:
  iterator insert( iterator i, const TYPE& val );
  void insert( input_iterator start, input_iterator end );
  iterator insert( const TYPE& val );

The function insert() either:
  • inserts val after the element at pos (where pos is really just a suggestion as to where val should go, since multisets and multimaps are ordered), and returns an iterator to that element.
  • inserts a range of elements from start to end.
  • inserts val into the multiset. The return value is an iterator to the element inserted, and a boolean describing whether an insertion took place.

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.

find() runs in logarithmic time.

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.

lower_bound() runs in logarithmic time.

Related topics:
upper_bound
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.

Related topics:
lower_bound
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 a point just after 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.

count
Syntax:
  size_type count( const key_type& key );

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

count() should run in logarithmic time.


C++ Priority Queues
Priority queue constructors
Syntax:
  priority_queue( const Compare& cmp = Compare(), const Container& c = Container() );
  priority_queue( input_iterator start, input_iterator end, const Compare& comp = Compare(), const Container& c = Container() );

Priority queues can be constructed with an optional compare function cmp' and an optional container c. If start and end are specified, the priority queue will be constructed with the elements between start and end.

empty
Syntax:
  bool empty() const;

The empty() function returns true if the priority queue has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a priority queue and display 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
size
Syntax:
  size_type size() const;

The size() function returns the number of elements in the current priority queue.

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
(C++ Multimaps) max_size
(C++ Strings) resize
pop
Syntax:
  void pop();

The function pop() removes the top element of the priority queue and discards it.

Related topics:
push
top
push
Syntax:
  void push( const TYPE& val );

The function push() adds val to the end of the current priority queue.

For example, the following code uses the push() function to add ten integers to the end of a queue:

   queue<int> q;
   for( int i=0; i < 10; i++ )
     q.push(i);

top
Syntax:
  TYPE& top();

The function top() returns a reference to the top element of the priority queue.

For example, the following code removes all of the elements from a stack and uses top() to display them:

   while( !s.empty() ) {
     cout << s.top() << " ";
     s.pop();
   }

Related topics:
pop


C++ Queues
Queue constructor
Syntax:
  queue();
  queue( const Container& con );

Queues have an empty constructor and a constructor that can be used to specify a container type.

empty
Syntax:
  bool empty() const;

The empty() function returns true if the queue has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a queue and display 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
size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
(C++ Multimaps) max_size
(C++ Strings) resize
front
Syntax:
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the queue, and runs in constant time.

Related topics:
back
(C++ Lists) pop_front
(C++ Lists) push_front
back
Syntax:
  TYPE& back();
  const TYPE& back() const;

The back() function returns a reference to the last element in the queue.

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

The back() function runs in constant time.

Related topics:
front
(C++ Lists) pop_back
push
Syntax:
  void push( const TYPE& val );

The function push() adds val to the end of the current queue.

For example, the following code uses the push() function to add ten integers to the end of a queue:

   queue<int> q;
   for( int i=0; i < 10; i++ )
     q.push(i);

pop
Syntax:
  void pop();

The function pop() removes the top element of the queue and discards it.

Related topics:
push
(C++ Priority Queues) top


C++ Sets
swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current set with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice
Container operators
Syntax:
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one set to another takes linear time.

Two sets are equal if:

  1. Their size is the same, and
  2. Each member in location i in one set is equal to the the member in location i in the other set.

Comparisons among sets are done lexicographically.

Related topics:
(C++ Strings) String operators
(C++ Strings) at
(C++ Lists) merge
(C++ Lists) unique
begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the set. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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
rbegin
rend
end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the set.

Note that before you can access the last element of the set using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.

Related topics:
begin
rbegin
rend
rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current set.

rbegin() runs in constant time.

Related topics:
begin
end
rend
rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current set.

rend() runs in constant time.

Related topics:
begin
end
rbegin
size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
max_size
(C++ Strings) resize
max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size
empty
Syntax:
  bool empty() const;

The empty() function returns true if the set has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a set and display 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
clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the set. clear() runs in linear time.

Related topics:
(C++ Lists) erase
Container constructors & destructors
Syntax:
  container();
  container( const container& c );
  ~container();

Every set has a default constructor, copy constructor, and destructor.

The default constructor takes no arguments, creates a new instance of that set, and runs in constant time. The default copy constructor runs in linear time and can be used to create a new set that is a copy of the given set c.

The default destructor is called when the set should be destroyed.

For example, the following code creates a pointer to a vector of integers and then uses the default set constructor to allocate a memory for a new vector:

 vector<int>* v;
 v = new vector<int>();

Related topics:
(C++ Strings) resize
key_comp
Syntax:
  key_compare key_comp() const;

The function key_comp() returns the function that compares keys.

key_comp() runs in constant time.

Related topics:
value_comp
value_comp
Syntax:
  value_compare value_comp() const;

The value_comp() function returns the function that compares values.

value_comp() runs in constant time.

Related topics:
key_comp
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 pos (where pos is really just a suggestion as to where val should go, since sets and maps are ordered), 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.

Related topics:
(C++ Maps) Map operators
find
Syntax:
  iterator find( const key_type& key );

The find() function returns an iterator to key, or an iterator to the end of the set if key is not found.

find() runs in logarithmic time.

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.

lower_bound() runs in logarithmic time.

Related topics:
upper_bound
upper_bound
Syntax:
  iterator upper_bound( const key_type& key );

The function upper_bound() returns an iterator to the first element in the set with a key greater than key.

Related topics:
lower_bound
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 a point just after 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.

count
Syntax:
  size_type count( const key_type& key );

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

count() should run in logarithmic time.


C++ Stacks
Stack constructors
Syntax:
  stack();
  stack( const Container& con );

Stacks have an empty constructor and a constructor that can be used to specify a container type.

empty
Syntax:
  bool empty() const;

The empty() function returns true if the stack has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a stack and display 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
size
Syntax:
  size_type size() const;

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

Related topics:
(C++ Strings) capacity
empty
(C++ Strings) length
(C++ Multimaps) max_size
(C++ Strings) resize
top
Syntax:
  TYPE& top();

The function top() returns a reference to the top element of the stack.

For example, the following code removes all of the elements from a stack and uses top() to display them:

   while( !s.empty() ) {
     cout << s.top() << " ";
     s.pop();
   }

Related topics:
pop
push
Syntax:
  void push( const TYPE& val );

The function push() adds val to the top of the current stack.

For example, the following code uses the push() function to add ten integers to the top of a stack:

   stack<int> s;
   for( int i=0; i < 10; i++ )
     s.push(i);

Related topics:
pop
pop
Syntax:
  void pop();

The function pop() removes the top element of the stack and discards it.

Related topics:
(C++ Priority Queues) push
top


C++ Strings
String operators
Syntax:
  bool operator==(const string& c1, const string& c2);
  bool operator!=(const string& c1, const string& c2);
  bool operator<(const string& c1, const string& c2);
  bool operator>(const string& c1, const string& c2);
  bool operator<=(const string& c1, const string& c2);
  bool operator>=(const string& c1, const string& c2);
  string operator+(const string& s1, const string& s2 );
  string operator+(const char* s, const string& s2 );
  string operator+( char c, const string& s2 );
  string operator+( const string& s1, const char* s );
  string operator+( const string& s1, char c );
  ostream& operator<<( ostream& os, const string& s );
  istream& operator>>( istream& is, string& s );
  string& operator=( const string& s );
  string& operator=( const char* s );
  string& operator=( char ch );
  char& operator[]( size_type index );

C++ strings can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Performing a comparison or assigning one string to another takes linear time.

Two strings are equal if:

  1. Their size is the same, and
  2. Each member in location i in one string is equal to the the member in location i in the other string.

Comparisons among strings are done lexicographically.

In addition to these normal (C++ Multimaps) Container operators, strings can also be concatenated with the + operator and fed to the C++ I/O stream classes with the << and >> operators.

For example, the following code concatenates two strings and displays the result:

 string s1 = "Now is the time...";
 string s2 = "for all good men...";
 string s3 = s1 + s2;
 cout << "s3 is " << s3 << endl;

Furthermore, strings can be assigned values that are other strings, character arrays, or even single characters. The following code is perfectly valid:

 char ch = 'N';
 string s = ch;

Individual characters of a string can be examined with the [] operator, which runs in constant time.

Related topics:
(C++ Multimaps) Container operators
c_str
compare
data
swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current string with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice
insert
Syntax:
  iterator insert( iterator i, const char& ch );
  string& insert( size_type index, const string& str );
  string& insert( size_type index, const char* str );
  string& insert( size_type index1, const string& str, size_type index2, size_type num );
  string& insert( size_type index, const char* str, size_type num );
  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:
erase
replace
begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the string. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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
rbegin
rend
end
Syntax:
  iterator end();
  const_iterator end() const;

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

Note that before you can access the last element of the string using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.

Related topics:
begin
rbegin
rend
rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

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

rbegin() runs in constant time.

Related topics:
begin
end
rend
rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current string.

rend() runs in constant time.

Related topics:
begin
end
rbegin
size
Syntax:
  size_type size() const;

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

Related topics:
capacity
empty
length
max_size
resize
max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size
empty
Syntax:
  bool empty() const;

The empty() function returns true if the string has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a string and display 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
clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the string. clear() runs in linear time.

Related topics:
(C++ Lists) erase
compare
Syntax:
  int compare( const string& str );
  int compare( const char* str );
  int compare( size_type index, size_type length, const string& str );
  int compare( size_type index, size_type length, const 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.

For example, the following code uses compare() to compare four strings with eachother:

 string names[] = {"Homer", "Marge", "3-eyed fish", "inanimate carbon rod"};
 for( int i = 0; i < 4; i++ ) {
   for( int j = 0; j < 4; j++ ) {
     cout << names[i].compare( names[j] ) << " ";
   }
   cout << endl;
 }

Data from the above code was used to generate this table, which shows how the various strings compare to eachother:

 | Homer | Marge | 3-eyed fish | inanimate carbon rod
"Homer".compare( x ) | 0 | -1 | 1 | -1
"Marge".compare( x ) | 1 | 0 | 1 | -1
"3-eyed fish".compare( x ) | -1 | -1 | 0 | -1
"inanimate carbon rod".compare( x ) | 1 | 1 | 1 | 0

Related topics:
String operators
erase
Syntax:
  string& erase( size_type index = 0, size_type num = npos );
  iterator erase( iterator loc );
  iterator erase( iterator start, iterator end );

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 ''

erase() runs in linear time.

Related topics:
insert
c_str
Syntax:
  const char* c_str();

The function c_str() returns a const pointer to a regular C string, identical to the current string. The returned string is null-terminated.

Note that since the returned pointer is of type (C/C++ Keywords) const, the character data that c_str() returns cannot be modified.

Related topics:
String operators
data
resize
Syntax:
  void resize( size_type num, const TYPE& val = TYPE() );

The function resize() changes the size of the string to size. If val is specified then any newly-created elements will be initialized to have a value of val.

This function runs in linear time.

Related topics:
(C++ Multimaps) Container constructors & destructors
capacity
size
substr
Syntax:
  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

Related topics:
copy
replace
Syntax:
  string& replace( size_type index, size_type num, const string& str );
  string& replace( size_type index1, size_type num1, const string& str, size_type index2, size_type num2 );
  string& replace( size_type index, size_type num, const char* str );
  string& replace( size_type index, size_type num1, const char* str, size_type num2 );
  string& replace( size_type index, size_type num1, size_type num2, char ch );
  string& replace( iterator start, iterator end, const string& str );
  string& replace( iterator start, iterator end, const char* str );
  string& replace( iterator start, iterator end, const char* str, size_type num );
  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
push_back
Syntax:
  void push_back( const TYPE& val );

The push_back() function appends val to the end of the string.

For example, the following code puts 10 integers into a list:

   list<int> the_list;
   for( int i = 0; i < 10; i++ )
     the_list.push_back( i );

When displayed, the resulting list would look like this:

 0 1 2 3 4 5 6 7 8 9

push_back() runs in constant time.

Related topics:
(C++ Lists) assign
(C++ Lists) insert
(C++ Lists) pop_back
(C++ Lists) push_front
append
Syntax:
  string& append( const string& str );
  string& append( const char* str );
  string& append( const string& str, size_type index, size_type len );
  string& append( const char* str, size_type num );
  string& append( size_type num, char ch );
  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 uses append() to add 10 copies of the '!' character to a string:

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

That code displays:

   Hello World!!!!!!!!!!

In the next example, append() is used to concatenate a substring of one string onto another string:

 string str1 = "Eventually I stopped caring...";
 string str2 = "but that was the '80s so nobody noticed.";
 str1.append( str2, 25, 15 );
 cout << "str1 is " << str1 << endl;

When run, the above code displays:

 str1 is Eventually I stopped caring...nobody noticed.

at
Syntax:
  TYPE& at( size_type loc );
  const TYPE& at( size_type loc ) const;

The at() function returns a reference to the element in the string at index loc. The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the string.

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:
(C++ Multimaps) Container operators
(C++ Double-ended Queues) Container operators
capacity
Syntax:
  size_type capacity() const;

The capacity() function returns the number of elements that the string can hold before it will need to allocate more space.

For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size, the other method calls the reserve function to achieve a similar goal:

 vector<int> v1(10);
 cout << "The capacity of v1 is " << v1.capacity() << endl;
 vector<int> v2;
 v2.reserve(20);
 cout << "The capacity of v2 is " << v2.capacity() << endl;

When run, the above code produces the following output:

 The capacity of v1 is 10
 The capacity of v2 is 20

C++ containers are designed to grow in size dynamically. This frees the programmer from having to worry about storing an arbitrary number of elements in a container. However, sometimes the programmer can improve the performance of her program by giving hints to the compiler about the size of the containers that the program will use. These hints come in the form of the reserve() function and the constructor used in the above example, which tell the compiler how large the container is expected to get.

The capacity() function runs in constant time.

Related topics:
reserve
resize
size
reserve
Syntax:
  void reserve( size_type size );

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

reserve() runs in linear time.

Related topics:
capacity
getline
Syntax:
  istream& getline( istream& is, string& s, char delimiter = '/n' );

The C++ string class defines the global function getline() to read strings from and I/O stream. The getline() function, which is not part of the string class, reads a line from is and stores it into s. If a character delimiter is specified, then getline() will use delimiter to decide when to stop reading data.

For example, the following code reads a line of text from STDIN and displays it to STDOUT:

 string s;
 getline( cin, s );
 cout << "You entered " << s << endl;

Related topics:
(C++ I/O) get
(C++ I/O) getline
String constructors
Syntax:
  string();
  string( const string& s );
  string( size_type length, const char& ch );
  string( const char* str );
  string( const char* str, size_type length );
  string( const string& str, size_type index, size_type length );
  string( input_iterator start, input_iterator end );
  ~string();

The string constructors create a new string containing:

  • nothing; an empty string,
  • a copy of the given string s,
  • 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
  • a string of characterss denoted by the start and end iterators

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

The string constructors usually run in linear time, except the empty constructor, which runs in constant time.

assign
Syntax:
  void assign( size_type num, const char& val );
  void assign( input_iterator start, input_iterator end );
  string& assign( const string& str );
  string& assign( const char* str );
  string& assign( const char* str, size_type num );
  string& assign( const string& str, size_type index, size_type len );
  string& assign( size_type num, const char& ch );

The deafult assign() function gives the current string the values from start to end, or gives it num copies of val.

In addition to the normal (C++ Lists) assign() functionality that all C++ containers have, strings possess an assign() function that also allows them to:

  • assign str to the current string,
  • assign the first num characters of str to the current string,
  • assign a substring of str starting at index that is len characters long 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

This function will destroy the previous contents of the string.

Related topics:
(C++ Lists) assign
length
Syntax:
  size_type length() const;

The length() function returns the number of elements in the current string, performing the same role as the size() function.

Related topics:
size
data
Syntax:
  const char *data();

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

Related topics:
String operators
c_str
copy
Syntax:
  size_type copy( char* str, size_type num, size_type index = 0 );

The copy() function copies num characters of the current string (starting at index if it's specified, 0 otherwise) into str.

The return value of copy() is the number of characters copied.

For example, the following code uses copy() to extract a substring of a string into an array of characters:

 char buf[30];
 memset( buf, '/0', 30 );
 string str = "Trying is the first step towards failure.";
 str.copy( buf, 24 );
 cout << buf << endl;

When run, this code displays:

 Trying is the first step

Note that before calling copy(), we first call (Standard C String and Character) memset() to fill the destination array with copies of the NULL character. This step is included to make sure that the resulting array of characters is NULL-terminated.

Related topics:
substr
find
Syntax:
  size_type find( const 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;

Related topics:
find_first_not_of
find_first_of
find_last_not_of
find_last_of
rfind
rfind
Syntax:
  size_type rfind( const 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 ch in the current string, doing a reverse 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
find_first_not_of
find_first_of
find_last_not_of
find_last_of
find_first_of
Syntax:
  size_type find_first_of( const 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
find_last_not_of
find_last_of
rfind
find_first_not_of
Syntax:
  size_type find_first_not_of( const 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.

For example, the following code searches a string of text for the first character that is not a lower-case character, space, comma, or hypen:

 string lower_case = "abcdefghijklmnopqrstuvwxyz ,-";
 string str = "this is the lower-case part, AND THIS IS THE UPPER-CASE PART";
 cout << "first non-lower-case letter in str at: " << str.find_first_not_of(lower_case) << endl;

When run, find_first_not_of() finds the first upper-case letter in str at index 29 and displays this output:

 first non-lower-case letter in str at: 29

Related topics:
find
find_first_not_of
find_first_of
find_last_not_of
find_last_of
rfind
find_last_of
Syntax:
  size_type find_last_of( const 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_first_not_of
find_first_of
find_last_not_of
rfind
find_last_not_of
Syntax:
  size_type find_last_not_of( const 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.

For example, the following code searches for the last non-lower-case character in a mixed string of characters:

 string lower_case = "abcdefghijklmnopqrstuvwxyz";
 string str = "abcdefgABCDEFGhijklmnop";
 cout << "last non-lower-case letter in str at: " << str.find_last_not_of(lower_case) << endl;

This code displays the following output:

 last non-lower-case letter in str at: 13


C++ Vectors
swap
Syntax:
  void swap( const container &from );

The swap() function exchanges the elements of the current vector with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

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

The above code displays:

   And this is second
   This comes first

Related topics:
(C++ Lists) splice
begin
Syntax:
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the vector. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // 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
rbegin
rend
end
Syntax:
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the vector.

Note that before you can access the last element of the vector using an iterator that you get from a call to end(), you'll have to decrement the iterator first.

For example, the following code uses begin() and end() to iterate through all of the members of a vector:

 vector<int> v1( 5, 789 );
 vector<int>::iterator it;
 for( it = v1.begin(); it != v1.end(); it++ ) {
   cout << *it << endl;
 }

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.

Related topics:
begin
rbegin
rend
rbegin
Syntax:
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current vector.

rbegin() runs in constant time.

Related topics:
begin
end
rend
rend
Syntax:
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current vector.

rend() runs in constant time.

Related topics:
begin
end
rbegin
size
Syntax:
  size_type size() const;

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

Related topics:
capacity
empty
(C++ Strings) length
max_size
resize
max_size
Syntax:
  size_type max_size() const;

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

Related topics:
size
empty
Syntax:
  bool empty() const;

The empty() function returns true if the vector has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a vector and display 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
clear
Syntax:
  void clear();

The function clear() deletes all of the elements in the vector. clear() runs in linear time.

Related topics:
erase
Container constructors
Syntax:
  container();
  container( const container& c );
  container( size_type num, const TYPE& val = TYPE() );
  container( input_iterator start, input_iterator end );
  ~container();

The default vector constructor takes no arguments, creates a new instance of that vector.

The second constructor is a default copy constructor that can be used to create a new vector that is a copy of the given vector c.

The third constructor creates a vector with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a vector consisting of five copies of the integer 42:

 vector<int> v1( 5, 42 );

The last constructor creates a vector that is initialized to contain the elements between start and end. For example:

 // create a vector of random integers
 cout << "original vector: ";
 vector<int> v;
 for( int i = 0; i < 10; i++ ) {
   int num = (int) rand() % 10;
   cout << num << " ";
   v.push_back( num );
 }
 cout << endl;
 // find the first element of v that is even
 vector<int>::iterator iter1 = v.begin();
 while( iter1 != v.end() && *iter1 % 2 != 0 ) {
   iter1++;
 }
 // find the last element of v that is even
 vector<int>::iterator iter2 = v.end();
 do {
   iter2--;
 } while( iter2 != v.begin() && *iter2 % 2 != 0 );
 cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;
 cout << "new vector: ";
 vector<int> v2( iter1, iter2 );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, this code displays the following output:

 original vector: 1 9 7 9 2 7 2 1 9 8
 first even number: 2, last even number: 8
 new vector: 2 7 2 1 9

All of these constructors run in linear time except the first, which runs in constant time.

The default destructor is called when the vector should be destroyed.

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

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.

For example, the following code uses assign() to put 10 copies of the integer 42 into a vector:

 vector<int> v;
 v.assign( 10, 42 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << v[i] << " ";
 }
 cout << endl;

The above code displays the following output:

 42 42 42 42 42 42 42 42 42 42

The next example shows how assign() can be used to copy one vector to another:

 vector<int> v1;
 for( int i = 0; i < 10; i++ ) {
   v1.push_back( i );
 }
 vector<int> v2;
 v2.assign( v1.begin(), v1.end() );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;

When run, the above code displays the following output:

 0 1 2 3 4 5 6 7 8 9

Related topics:
(C++ Strings) assign
insert
push_back
(C++ Lists) push_front
resize
Syntax:
  void resize( size_type num, const TYPE& val = TYPE() );

The function resize() changes the size of the vector to size. If val is specified then any newly-created elements will be initialized to have a value of val.

This function runs in linear time.

Related topics:
(C++ Multimaps) Container constructors & destructors
capacity
size
insert
Syntax:
  iterator insert( iterator loc, const TYPE& val );
  void insert( iterator loc, size_type num, const TYPE& val );
  template<TYPE> void insert( iterator loc, input_iterator start, input_iterator end );

The insert() function either:

  • inserts val before loc, returning an iterator to the element inserted,
  • 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

Related topics:
assign
erase
(C++ Lists) merge
push_back
(C++ Lists) push_front
(C++ Lists) splice
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.

The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, dequeues, and strings. The multiple-element version of erase always takes linear time.

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

In the next example, erase() is called with two iterators to delete a range of elements from a vector:

 // 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 );
 }
 // display the complete vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;
 // use erase to remove all but the first two and last three elements
 // of the vector
 alphaVector.erase( alphaVector.begin()+2, alphaVector.end()-3 );
 // display the modified vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;

When run, the above code displays:

 ABCDEFGHIJ
 ABHIJ

Related topics:
clear
insert
pop_back
(C++ Lists) pop_front
(C++ Lists) remove
(C++ Lists) remove_if
front
Syntax:
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the vector, and runs in constant time.

Related topics:
back
(C++ Lists) pop_front
(C++ Lists) push_front
back
Syntax:
  TYPE& back();
  const TYPE& back() const;

The back() function returns a reference to the last element in the 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

The back() function runs in constant time.

Related topics:
front
pop_back
push_back
Syntax:
  void push_back( const TYPE& val );

The push_back() function appends val to the end of the vector.

For example, the following code puts 10 integers into a list:

   list<int> the_list;
   for( int i = 0; i < 10; i++ )
     the_list.push_back( i );

When displayed, the resulting list would look like this:

 0 1 2 3 4 5 6 7 8 9

push_back() runs in constant time.

Related topics:
assign
insert
pop_back
(C++ Lists) push_front
pop_back
Syntax:
  void pop_back();

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

pop_back() runs in constant time.

Related topics:
back
erase
(C++ Lists) pop_front
push_back
Container operators
Syntax:
  TYPE& operator[]( size_type index );
  const TYPE& operator[]( size_type index ) const;
  container operator=(const container& c2);
  bool operator==(const container& c1, const container& c2);
  bool operator!=(const container& c1, const container& c2);
  bool operator<(const container& c1, const container& c2);
  bool operator>(const container& c1, const container& c2);
  bool operator<=(const container& c1, const container& c2);
  bool operator>=(const container& c1, const container& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Individual elements of a vector can be examined with the [] operator.

Performing a comparison or assigning one vector to another takes linear time. The [] operator runs in constant time.

Two `containers` 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.

For example, the following code uses the [] operator to access all of the elements of a vector:

 vector<int> v( 5, 1 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << "Element " << i << " is " << v[i] << endl;
 }

Related topics:
at
at
Syntax:
  TYPE& at( size_type loc );
  const TYPE& at( size_type loc ) const;

The at() function returns a reference to the element in the vector at index 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:
(C++ Multimaps) Container operators
Container operators
capacity
Syntax:
  size_type capacity() const;

The capacity() function returns the number of elements that the vector can hold before it will need to allocate more space.

For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size, the other method calls the reserve function to achieve a similar goal:

 vector<int> v1(10);
 cout << "The capacity of v1 is " << v1.capacity() << endl;
 vector<int> v2;
 v2.reserve(20);
 cout << "The capacity of v2 is " << v2.capacity() << endl;

When run, the above code produces the following output:

 The capacity of v1 is 10
 The capacity of v2 is 20

C++ containers are designed to grow in size dynamically. This frees the programmer from having to worry about storing an arbitrary number of elements in a container. However, sometimes the programmer can improve the performance of her program by giving hints to the compiler about the size of the containers that the program will use. These hints come in the form of the reserve() function and the constructor used in the above example, which tell the compiler how large the container is expected to get.

The capacity() function runs in constant time.

Related topics:
reserve
resize
size
reserve
Syntax:
  void reserve( size_type size );

The reserve() function sets the capacity of the vector to at least size.

reserve() runs in linear time.

Related topics:
capacity


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.

Related topics:
register
bool

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

For example, the following code declares a boolean variable called done, initializes it to false, and then loops until that variable is set to true.

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

Also see the data types page.

Related topics:
char
double
false
float
int
long
short
signed
true
unsigned
wchar_t
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.

Related topics:
continue
do
for
goto
switch
while
case

The case keyword is used to test a variable against a certain value in a 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. For more information about variable types, see the data types page.

Related topics:
bool
double
float
int
long
short
signed
unsigned
void
wchar_t
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:
friend
private
protected
public
struct
this
typename
union
virtual
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
mutable
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:
const
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:
(Standard C Memory) free
(Standard C Memory) malloc
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:
break
continue
for
while
double

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

Related topics:
bool
char
float
int
long
short
signed
unsigned
void
wchar_t
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.

Related topics:
if
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.

Related topics:
bool
char
double
int
long
short
signed
unsigned
void
wchar_t
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:
break
continue
do
if
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.

Related topics:
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
switch
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, switch statements, 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.

Related topics:
bool
char
double
float
long
short
signed
unsigned
void
wchar_t
long

The long keyword is a data type modifier that is used to declare long integer variables. For more information on long, see the data types page.

Related topics:
bool
char
double
float
int
short
signed
void
mutable

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

Related topics:
const
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;
     ...
   }

Related topics:
using
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
(Standard C Memory) free
(Standard C Memory) malloc
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.

Related topics:
this
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:
class
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:
class
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:
class
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:
bool
char
double
float
int
long
signed
unsigned
void
wchar_t
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:
bool
char
double
float
int
long
short
unsigned
void
wchar_t
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, the following code uses a template to define a generic swap function that can swap two variables of any type:

   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 );
   }

Related topics:
typename
this

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

Related topics:
class
operator
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. This statement, 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.

Related topics:
class
template
union
Syntax:
  union union-name {
  public-members-list;
  private:
  private-members-list;
  } object-list;

A union is like a class, 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:
bool
char
double
float
int
short
signed
void
wchar_t
using

The using keyword is used to import a namespace (or parts of a namespace) into the current scope.

For example, the following code imports the entire std namespace into the current scope so that items within that namespace can be used without a preceeding "std::".

 using namespace std;

Alternatively, the next code snippet just imports a single element of the std namespace into the current namespace:

 using std::cout;

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 virtual 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 virtual function run.

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

Related topics:
class
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.

Related topics:
char
double
float
int
long
short
signed
unsigned
wchar_t
wchar_t

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

Related topics:
bool
char
double
float
int
short
signed
unsigned
void
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.

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;
     }
   }


C/C++ 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.

Related topics:
#define
#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.

Related topics:
#, ##
#if, #ifdef, #ifndef, #else, #elif, #endif
#undef
#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 and removing a million "cout"s in your code.

Related topics:
#define
#include
Syntax:
  #include <filename>
  #include "filename"

This command slurps in a file and inserts it at the current location. The main difference between the syntax of the two items 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.

Related topics:
#define
Predefined preprocessor 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++.


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

An example:

   Mon Jun 26 12:03:53 2000

Related topics:
clock
ctime
difftime
gmtime
localtime
mktime
time
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:
asctime
ctime
time
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:
asctime
clock
ctime
difftime
gmtime
localtime
mktime
(Other Standard C Functions) srand
strftime
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

using ctime() is equivalent to

   asctime( localtime( tp ) );

Related topics:
asctime
clock
gmtime
localtime
mktime
time
localtime
Syntax:
  #include <time.h>
  struct tm *localtime( const time_t *time );

The function localtime() converts calendar time time into local time. Watch out for the static return.

Related topics:
asctime
ctime
difftime
gmtime
strftime
time
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. Watch out for static return.

Related topics:
asctime
ctime
difftime
localtime
mktime
strftime
time
difftime
Syntax:
  #include <time.h>
  double difftime( time_t time2, time_t time1 );

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

Related topics:
asctime
gmtime
localtime
time
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:
asctime
ctime
gmtime
time
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:
gmtime
localtime
time
setlocale
Syntax:
  #include <locale.h>
  char *setlocale( int category, const char * locale );

The setlocale() function is used to set and retrieve the current locale. If locale is NULL, the current locale is returned. Otherwise, locale is used to set the locale for the given category.

category can have the following values:

Value | Description
LC_ALL | All of the locale
LC_TIME | Date and time formatting
LC_NUMERIC | Number formatting
LC_COLLATE | String collation and regular expression matching
LC_CTYPE | Regular expression matching, conversion, case-sensitive comparison, wide character functions, and character classification.
LC_MONETARY | For monetary formatting
LC_MESSAGES | For natural language messages

Related topics:
(Standard C String and Character) strcoll


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
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:
fflush
fopen
freopen
setbuf
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
getc
perror
putc
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
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:
fopen
fputc
fread
fwrite
getc
getchar
gets
putc
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:
fseek
fsetpos
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.

Related topics:
fputs
fscanf
gets
scanf
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 );

Related topics:
fclose
fflush
fgetc
fputc
fread
freopen
fseek
getc
getchar
setbuf
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:
fputc
fputs
fscanf
printf
sprintf
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
fwrite
getc
getchar
putc
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
fprintf
fscanf
gets
puts
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. You can use feof() or ferror() to figure out if an error occurs.

Related topics:
fflush
fgetc
fopen
fputc
fscanf
fwrite
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:
fclose
fopen
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:
fgets
fprintf
fputs
fread
fwrite
scanf
sscanf
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):

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

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:
fgetpos
fopen
fsetpos
ftell
rewind
fsetpos
Syntax:
  #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
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:
fgetpos
fseek
fsetpos
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:
fflush
fgetc
fputc
fread
fscanf
getc
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:
feof
fflush
fgetc
fopen
fputc
fread
fwrite
putc
ungetc
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:
fgetc
fopen
fputc
putc
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:
fgetc
fgets
fputs
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.

Related topics:
clearerr
feof
ferror
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:
fprintf
puts
scanf
sprintf
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:
feof
fflush
fgetc
fputc
getc
getchar
putchar
puts
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:
fputs
gets
printf
putc
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:
fgets
fscanf
printf
sscanf
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 be BUFSIZ characters long.

Related topics:
fclose
fopen
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" );

Note that sprintf() does the opposite of a function like (Standard C String and Character) atoi() -- where (Standard C String and Character) atoi() converts a string into a number, sprintf() can be used to convert a number into a string.

For example, the following code uses sprintf() to convert an integer into a string of characters:

   char result[100];
   int num=24;
   sprintf( result, "%d", num );

Related topics:
(Standard C String and Character) atof
(Standard C String and Character) atoi
(Standard C String and Character) atol
fprintf
printf
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:
fscanf
scanf
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
(C++ I/O) putback
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 (Other Standard C Functions) 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 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:
fabs
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
cos
cosh
sin
sinh
tan
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
cos
cosh
sin
sinh
tan
tanh
atan
Syntax:
  #include <math.h>
  double atan( double arg );

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

Related topics:
acos
asin
atan2
cos
cosh
sin
sinh
tan
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.

Note the order of the arguments passed to this function.

Related topics:
acos
asin
atan
cos
cosh
sin
sinh
tan
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
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:
acos
asin
atan
atan2
cosh
sin
sinh
tan
tanh
cosh
Syntax:
  #include <math.h>
  double cosh( double arg );

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

Related topics:
acos
asin
atan
atan2
cos
sin
sinh
tan
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
pow
sqrt
fabs
Syntax:
  #include <math.h>
  double fabs( double arg );

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

Related topics:
abs
fmod
labs
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
fmod
Syntax:
  #include <math.h>
  double fmod( double x, double y );

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

Related topics:
ceil
fabs
floor
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
modf
labs
Syntax:
  #include <stdlib.h>
  long labs( long num );

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

Related topics:
abs
fabs
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
modf
ldiv
Syntax:
  #include <stdlib.h>
  ldiv_t ldiv( long numerator, long denominator );

Testing: adiv_t, div_t, ldiv_t.

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:
exp
log10
pow
sqrt
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
ldexp
pow
Syntax:
  #include <math.h>
  double pow( double base, double exp );

The pow() function returns base raised to the expth 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 an overflow occurs.

Related topics:
exp
log
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:
acos
asin
atan
atan2
cos
cosh
sinh
tan
tanh
sinh
Syntax:
  #include <math.h>
  double sinh( double arg );

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

Related topics:
acos
asin
atan
atan2
cos
cosh
sin
tan
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
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:
acos
asin
atan
atan2
cos
cosh
sin
sinh
tanh
tanh
Syntax:
  #include <math.h>
  double tanh( double arg );

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


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
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
(C/C++ Keywords) delete
malloc
(C/C++ Keywords) new
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:
calloc
(C/C++ Keywords) delete
free
(C/C++ Keywords) new
realloc
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.


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:
assert
atexit
exit
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 non-zero on failure.

Related topics:
abort
exit
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:
abort
atexit
system
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.

Related topics:
raise
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
(Standard C Date & Time) 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
getenv
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.


Standard C String and 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
atol
(Standard C I/O) sprintf
strtod
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.

You can use (Standard C I/O) sprintf() to convert a number into a string.

Related topics:
atof
atol
(Standard C I/O) sprintf
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
atoi
(Standard C I/O) sprintf
strtol
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
isspace
isxdigit
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
isspace
isxdigit
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
isspace
isxdigit
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
isspace
isxdigit
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
isspace
isxdigit
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
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
isspace
isxdigit
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
isprint
ispunct
isxdigit
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:
islower
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
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:
memcmp
memcpy
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
memset
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. The return value of memcpy() is to. The behavior of memcpy() is undefined if to and from overlap.

Related topics:
memchr
memcmp
memmove
memset
strcpy
strlen
strncpy
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
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
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
strcpy
strncat
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:
strcat
strcmp
strcpy
strlen
strncat
strncmp
strncpy
strpbrk
strspn
strstr
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
strcat
strchr
strcoll
strcpy
strlen
strncmp
strxfrm
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 (Standard C Date & Time) setlocale() function.

Related topics:
(Standard C Date & Time) setlocale
strcmp
strxfrm
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
strcat
strchr
strcmp
strncmp
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:
strpbrk
strrchr
strstr
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
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
strchr
strncmp
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:
strchr
strcmp
strcpy
strlen
strncat
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
strcpy
strncat
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 no such characters are present.

Related topics:
(C++ Algorithms) find_first_of
strchr
strcspn
strrchr
strspn
strstr
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:
strcspn
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:
strchr
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:
memchr
strchr
strcspn
strpbrk
strrchr
strspn
strtok
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
strspn
strstr
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
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>

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

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

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

Related topics:
tolower