Sun Studio 12: C++ User's Guide

Chapter 13 Using The C++ Standard Library

When compiling in default (standard) mode, the compiler has access to the complete library specified by the C++ standard. The library components include what is informally known as the Standard Template Library (STL), as well as the following components.

The term STL does not have a formal definition, but is usually understood to include containers, iterators, and algorithms. The following subset of the standard library headers can be thought of as comprising the STL.

The C++ standard library (libCstd) is based on the RogueWaveTM Standard C++ Library, Version 2. This library is available only for the default mode (-compat=5) of the compiler and is not supported with use of the -compat[=4] option.

The C++ compiler also supports STLport’s Standard Library implementation version 4.5.3. libCstd is still the default library, but STLport’s product is available as an alternative. See 13.3 STLport for more information.

If you need to use your own version of the C++ standard library instead of one of the versions that is supplied with the compiler, you can do so by specifying the -library=no%Cstd option. Replacing the standard library that is distributed with the compiler is risky, and good results are not guaranteed. For more information, see 12.7 Replacing the C++ Standard Library.

For details about the standard library, see the Standard C++ Library User’s Guide and the Standard C++ Class Library Reference. Accessing Sun Studio Documentation in “Before You Begin” at the front of this book contains information about accessing this documentation. For a list of available books about the C++ standard library see Commercially Available Books in “Before You Begin.”

13.1 C++ Standard Library Header Files

Table 13–1 lists the headers for the complete standard library along with a brief description of each.

Table 13–1 C++ Standard Library Header Files

Header File 

Description 

<algorithm>

Standard algorithms that operate on containers 

<bitset>

Fixed-size sequences of bits 

<complex>

The numeric type representing complex numbers 

<deque>

Sequences supporting addition and removal at each end 

<exception>

Predefined exception classes 

<fstream>

Stream I/O on files 

<functional>

Function objects 

<iomanip>

iostream manipulators

<ios>

iostream base classes

<iosfwd>

Forward declarations of iostream classes

<iostream>

Basic stream I/O functionality 

<istream>

Input I/O streams 

<iterator>

Class for traversing a sequence 

<limits>

Properties of numeric types 

<list>

Ordered sequences 

<locale>

Support for internationalization 

<map>

Associative containers with key/value pairs 

<memory>

Special memory allocators 

<new>

Basic memory allocation and deallocation 

<numeric>

Generalized numeric operations 

<ostream>

Output I/O streams 

<queue>

Sequences supporting addition at the head and removal at the tail 

<set>

Associative container with unique keys 

<sstream>

Stream I/O using an in-memory string as source or sink 

<stack>

Sequences supporting addition and removal at the head 

<stdexcept>

Additional standard exception classes 

<streambuf>

Buffer classes for iostreams 

<string>

Sequences of characters 

<typeinfo>

Run-time type identification 

<utility>

Comparison operators 

<valarray>

Value arrays useful for numeric programming 

<vector>

Sequences supporting random access 

13.2 C++ Standard Library Man Pages

Table 13–2 lists the documentation available for each of the components of the standard library.

Table 13–2 Man Pages for C++ Standard Library

Man Page 

Overview 

Algorithms

Generic algorithms for performing various operations on containers and sequences 

Associative_Containers

Ordered containers 

Bidirectional_Iterators

An iterator that can both read and write and can traverse a container in both directions 

Containers

A standard template library (STL) collection 

Forward_Iterators

A forward-moving iterator that can both read and write 

Function_Objects

Object with an operator() defined

Heap_Operations

See entries for make_heap, pop_heap, push_heap and sort_heap

Input_Iterators

A read-only, forward moving iterator 

Insert_Iterators

An iterator adaptor that allows an iterator to insert into a container rather than overwrite elements in the container 

Iterators

Pointer generalizations for traversal and modification of collections 

Negators

Function adaptors and function objects used to reverse the sense of predicate function objects 

Operators

Operators for the C++ Standard Template Library Output 

Output_Iterators

A write-only, forward moving iterator 

Predicates

A function or a function object that returns a boolean (true/false) value or an integer value 

Random_Access_Iterators

An iterator that reads, writes, and allows random access to a container 

Sequences

A container that organizes a set of sequences 

Stream_Iterators

Includes iterator capabilities for ostreams and istreams that allow generic algorithms to be used directly on streams 

__distance_type

Determines the type of distance used by an iterator— obsolete 

__iterator_category

Determines the category to which an iterator belongs—obsolete 

__reverse_bi_iterator

An iterator that traverses a collection backwards 

accumulate

Accumulates all elements within a range into a single value 

adjacent_difference

Outputs a sequence of the differences between each adjacent pair of elements in a range 

adjacent_find

Find the first adjacent pair of elements in a sequence that are equivalent 

advance

Moves an iterator forward or backward (if available) by a certain distance 

allocator

The default allocator object for storage management in Standard Library containers 

auto_ptr

A simple, smart pointer class 

back_insert_iterator

An insert iterator used to insert items at the end of a collection 

back_inserter

An insert iterator used to insert items at the end of a collection 

basic_filebuf

Class that associates the input or output sequence with a file 

basic_fstream

Supports reading and writing of named files or devices associated with a file descriptor 

basic_ifstream

Supports reading from named files or other devices associated with a file descriptor 

basic_ios

A base class that includes the common functions required by all streams 

basic_iostream

Assists in formatting and interpreting sequences of characters controlled by a stream buffer 

basic_istream

Assists in reading and interpreting input from sequences controlled by a stream buffer 

basic_istringstream

Supports reading objects of class basic_string<charT,traits,Allocator> from an array in memory

basic_ofstream

Supports writing into named files or other devices associated with a file descriptor 

basic_ostream

Assists in formatting and writing output to sequences controlled by a stream buffer 

basic_ostringstream

Supports writing objects of class basic_string<charT,traits,Allocator>

basic_streambuf

Abstract base class for deriving various stream buffers to facilitate control of character sequences 

basic_string

A templatized class for handling sequences of character-like entities 

basic_stringbuf

Associates the input or output sequence with a sequence of arbitrary characters 

basic_stringstream

Supports writing and reading objects of class basic_string<charT,traits,Allocator> to or from an array in memory

binary_function

Base class for creating binary function objects 

binary_negate

A function object that returns the complement of the result of its binary predicate 

binary_search

Performs a binary search for a value on a container 

bind1st

Templatized utilities to bind values to function objects 

bind2nd

Templatized utilities to bind values to function objects 

binder1st

Templatized utilities to bind values to function objects 

binder2nd

Templatized utilities to bind values to function objects 

bitset

A template class and related functions for storing and manipulating fixed-size sequences of bits 

cerr

Controls output to an unbuffered stream buffer associated with the object stderr declared in <cstdio>

char_traits

A traits class with types and operations for the basic_string container and iostream classes

cin

Controls input from a stream buffer associated with the object stdin declared in <cstdio>

clog

Controls output to a stream buffer associated with the object stderr declared in <cstdio>

codecvt

A code conversion facet 

codecvt_byname

A facet that includes code set conversion classification facilities based on the named locales 

collate

A string collation, comparison, and hashing facet 

collate_byname

A string collation, comparison, and hashing facet 

compare

A binary function or a function object that returns true or false 

complex

C++ complex number library 

copy

Copies a range of elements 

copy_backward

Copies a range of elements 

count

Count the number of elements in a container that satisfy a given condition 

count_if

Count the number of elements in a container that satisfy a given condition 

cout

Controls output to a stream buffer associated with the object stdout declared in <cstdio>

ctype

A facet that includes character classification facilities 

ctype_byname

A facet that includes character classification facilities based on the named locales 

deque

A sequence that supports random access iterators and efficient insertion/deletion at both beginning and end 

distance

Computes the distance between two iterators 

divides

Returns the result of dividing its first argument by its second 

equal

Compares two ranges for equality 

equal_range

Finds the largest subrange in a collection into which a given value can be inserted without violating the ordering of the collection 

equal_to

A binary function object that returns true if its first argument equals its second 

exception

A class that supports logic and runtime errors 

facets

A family of classes used to encapsulate categories of locale functionality 

filebuf

Class that associates the input or output sequence with a file 

fill

Initializes a range with a given value 

fill_n

Initializes a range with a given value 

find

Finds an occurrence of value in a sequence 

find_end

Finds the last occurrence of a sub-sequence in a sequence 

find_first_of

Finds the first occurrence of any value from one sequence in another sequence 

find_if

Finds an occurrence of a value in a sequence that satisfies a specified predicate 

for_each

Applies a function to each element in a range 

fpos

Maintains position information for the iostream classes 

front_insert_iterator

An insert iterator used to insert items at the beginning of a collection 

front_inserter

An insert iterator used to insert items at the beginning of a collection 

fstream

Supports reading and writing of named files or devices associated with a file descriptor 

generate

Initialize a container with values produced by a value-generator class 

generate_n

Initialize a container with values produced by a value-generator class 

get_temporary_buffer

Pointer based primitive for handling memory 

greater

A binary function object that returns true if its first argument is greater than its second 

greater_equal

A binary function object that returns true if its first argument is greater than or equal to its second 

gslice

A numeric array class used to represent a generalized slice from an array 

gslice_array

A numeric array class used to represent a BLAS-like slice from a valarray

has_facet

A function template used to determine if a locale has a given facet 

ifstream

Supports reading from named files or other devices associated with a file descriptor 

includes

A basic set of operation for sorted sequences 

indirect_array

A numeric array class used to represent elements selected from a valarray 

inner_product

Computes the inner product A X B of two ranges A and B 

inplace_merge

Merges two sorted sequences into one 

insert_iterator

An insert iterator used to insert items into a collection rather than overwrite the collection 

inserter

An insert iterator used to insert items into a collection rather than overwrite the collection 

ios

A base class that includes the common functions required by all streams 

ios_base

Defines member types and maintains data for classes that inherit from it 

iosfwd

Declares the input/output library template classes and specializes them for wide and tiny characters 

isalnum

Determines if a character is alphabetic or numeric 

isalpha

Determines if a character is alphabetic 

iscntrl

Determines if a character is a control character 

isdigit

Determines if a character is a decimal digit 

isgraph

Determines if a character is a graphic character 

islower

Determines whether a character is lower case 

isprint

Determines if a character is printable 

ispunct

Determines if a character is punctuation 

isspace

Determines if a character is a space 

istream

Assists in reading and interpreting input from sequences controlled by a stream buffer 

istream_iterator

A stream iterator that has iterator capabilities for istreams 

istreambuf_iterator

Reads successive characters from the stream buffer for which it was constructed 

istringstream

Supports reading objects of class basic_string<charT,traits,Alocator>from an array in memory

istrstream

Reads characters from an array in memory 

isupper

Determines whether a character is upper case 

isxdigit

Determines whether a character is a hexadecimal digit 

iter_swap

Exchanges values in two locations 

iterator

A base iterator class 

iterator_traits

Returns basic information about an iterator 

less

A binary function object that returns true if tis first argument is less than its second 

less_equal

A binary function object that returns true if its first argument is less than or equal to its second 

lexicographical_compare

Compares two ranges lexicographically 

limits

Refer to numeric_limits

list

A sequence that supports bidirectional iterators 

locale

A localization class containing a polymorphic set of facets 

logical_and

A binary function object that returns true if both of its arguments are true 

logical_not

A unary function object that returns true if its argument is false 

logical_or

A binary function object that returns true if either of its arguments are true 

lower_bound

Determines the first valid position for an element in a sorted container 

make_heap

Creates a heap 

map

An associative container with access to non-key values using unique keys 

mask_array

A numeric array class that gives a masked view of a valarray 

max

Finds and returns the maximum of a pair of values 

max_element

Finds the maximum value in a range 

mem_fun

Function objects that adapt a pointer to a member function, to take the place of a global function 

mem_fun1

Function objects that adapt a pointer to a member function, to take the place of a global function 

mem_fun_ref

Function objects that adapt a pointer to a member function, to take the place of a global function 

mem_fun_ref1

Function objects that adapt a pointer to a member function, to take the place of a global function 

merge

Merges two sorted sequences into a third sequence 

messages

Messaging facets 

messages_byname

Messaging facets 

min

Finds and returns the minimum of a pair of values 

min_element

Finds the minimum value in a range 

minus

Returns the result of subtracting its second argument from its first 

mismatch

Compares elements from two sequences and returns the first two elements that don’t match each other 

modulus

Returns the remainder obtained by dividing the first argument by the second argument 

money_get

Monetary formatting facet for input 

money_put

Monetary formatting facet for output 

moneypunct

Monetary punctuation facets 

moneypunct_byname

Monetary punctuation facets 

multimap

An associative container that gives access to non-key values using keys 

multiplies

A binary function object that returns the result of multiplying its first and second arguments 

multiset

An associative container that allows fast access to stored key values 

negate

Unary function object that returns the negation of its argument 

next_permutation

Generates successive permutations of a sequence based on an ordering function 

not1

A function adaptor used to reverse the sense of a unary predicate function object 

not2

A function adaptor used to reverse the sense of a binary predicate function object 

not_equal_to

A binary function object that returns true if its first argument is not equal to its second 

nth_element

Rearranges a collection so that all elements lower in sorted order than the nth element come before it and all elements higher in sorter order than the nth element come after it

num_get

A numeric formatting facet for input 

num_put

A numeric formatting facet for output 

numeric_limits

A class for representing information about scalar types 

numpunct

A numeric punctuation facet 

numpunct_byname

A numeric punctuation facet 

ofstream

Supports writing into named files or other devices associated with a file descriptor 

ostream

Assists in formatting and writing output to sequences controlled by a stream buffer 

ostream_iterator

Stream iterators allow for use of iterators with ostreams and istreams 

ostreambuf_iterator

Writes successive characters onto the stream buffer object from which it was constructed 

ostringstream

Supports writing objects of class basic_string<charT,traits,Allocator>

ostrstream

Writes to an array in memory 

pair

A template for heterogeneous pairs of values 

partial_sort

Templatized algorithm for sorting collections of entities 

partial_sort_copy

Templatized algorithm for sorting collections of entities 

partial_sum

Calculates successive partial sums of a range of values 

partition

Places all of the entities that satisfy the given predicate before all of the entities that do not 

permutation

Generates successive permutations of a sequence based on an ordering function 

plus

A binary function object that returns the result of adding its first and second arguments 

pointer_to_binary_function

A function object that adapts a pointer to a binary function, to take the place of a binary_function

pointer_to_unary_function

A function object class that adapts a pointer to a function, to take the place of a unary_function

pop_heap

Moves the largest element off the heap 

prev_permutation

Generates successive permutations of a sequence based on an ordering function 

priority_queue

A container adapter that behaves like a priority queue 

ptr_fun

A function that is overloaded to adapt a pointer to a function, to take the place of a function 

push_heap

Places a new element into a heap 

queue

A container adaptor that behaves like a queue (first in, first out) 

random_shuffle

Randomly shuffles elements of a collection 

raw_storage_iterator

Enables iterator-based algorithms to store results into uninitialized memory 

remove

Moves desired elements to the front of a container, and returns an iterator that describes where the sequence of desired elements ends 

remove_copy

Moves desired elements to the front of a container, and returns an iterator that describes where the sequence of desired elements ends 

remove_copy_if

Moves desired elements to the front of a container, and returns an iterator that describes where the sequence of desired elements ends 

remove_if

Moves desired elements to the front of a container, and returns an iterator that describes where the sequence of desired elements ends 

replace

Substitutes elements in a collection with new values 

replace_copy

Substitutes elements in a collection with new values, and moves the revised sequence into result 

replace_copy_if

Substitutes elements in a collection with new values, and moves the revised sequence into result 

replace_if

Substitutes elements in a collection with new values 

return_temporary_buffer

A pointer-based primitive for handling memory 

reverse

Reverses the order of elements in a collection 

reverse_copy

Reverses the order of elements in a collection while copying them to a new collection 

reverse_iterator

An iterator that traverses a collection backwards 

rotate

Swaps the segment that contains elements from first through middle-minus-one with the segment that contains the elements from middle through last 

rotate_copy

Swaps the segment that contains elements from first through middle-minus-one with the segment that contains the elements from middle through last 

search

Finds a sub-sequence within a sequence of values that is element-wise equal to the values in an indicated range 

search_n

Finds a sub-sequence within a sequence of values that is element-wise equal to the values in an indicated range 

set

An associative container that supports unique keys 

set_difference

A basic set operation for constructing a sorted difference 

set_intersection

A basic set operation for constructing a sorted intersection 

set_symmetric_difference

A basic set operation for constructing a sorted symmetric difference 

set_union

A basic set operation for constructing a sorted union 

slice

A numeric array class for representing a BLAS-like slice from an array 

slice_array

A numeric array class for representing a BLAS-like slice from a valarray

smanip

Helper classes used to implement parameterized manipulators 

smanip_fill

Helper classes used to implement parameterized manipulators 

sort

A templatized algorithm for sorting collections of entities 

sort_heap

Converts a heap into a sorted collection 

stable_partition

Places all of the entities that satisfy the given predicate before all of the entities that do not, while maintaining the relative order of elements in each group 

stable_sort

A templatized algorithm for sorting collections of entities 

stack

A container adapter that behaves like a stack (last in, first out) 

streambuf

Abstract base class for deriving various stream buffers to facilitate control of character sequences 

string

A typedef for basic_string<char, char_traits<char>, allocator<char>>

stringbuf

Associates the input or output sequence with a sequence of arbitrary characters 

stringstream

Supports writing and reading objects of class basic_string<charT,traits,Alocator>to/from an array in memory

strstream

Reads and writes to an array in memory 

strstreambuf

Associates either the input sequence or the output sequence with a tiny character array whose elements store arbitrary values 

swap

Exchanges values 

swap_ranges

Exchanges a range of values in one location with those in another 

time_get

A time formatting facet for input 

time_get_byname

A time formatting facet for input, based on the named locales 

time_put

A time formatting facet for output 

time_put_byname

A time formatting facet for output, based on the named locales 

tolower

Converts a character to lower case. 

toupper

Converts a character to upper case 

transform

Applies an operation to a range of values in a collection and stores the result 

unary_function

A base class for creating unary function objects 

unary_negate

A function object that returns the complement of the result of its unary predicate 

uninitialized_copy

An algorithm that uses construct to copy values from one range to another location 

uninitialized_fill

An algorithm that uses the construct algorithm for setting values in a collection 

uninitialized_fill_n

An algorithm that uses the construct algorithm for setting values in a collection 

unique

Removes consecutive duplicates from a range of values and places the resulting unique values into the result 

unique_copy

Removes consecutive duplicates from a range of values and places the resulting unique values into the result 

upper_bound

Determines the last valid position for a value in a sorted container 

use_facet

A template function used to obtain a facet 

valarray

An optimized array class for numeric operations 

vector

A sequence that supports random access iterators 

wcerr

Controls output to an unbuffered stream buffer associated with the object stderr declared in <cstdio>

wcin

Controls input from a stream buffer associated with the object stdin declared in <cstdio>

wclog

Controls output to a stream buffer associated with the object stderr declared in <cstdio>

wcout

Controls output to a stream buffer associated with the object stdout declared in <cstdio>

wfilebuf

Class that associates the input or output sequence with a file 

wfstream

Supports reading and writing of named files or devices associated with a file descriptor 

wifstream

Supports reading from named files or other devices associated with a file descriptor 

wios

A base class that includes the common functions required by all streams 

wistream

Assists in reading and interpreting input from sequences controlled by a stream buffer 

wistringstream

Supports reading objects of class basic_string<charT,traits,Allocator>from an array in memory

wofstream

Supports writing into named files or other devices associated with a file descriptor 

wostream

Assists in formatting and writing output to sequences controlled by a stream buffer 

wostringstream

Supports writing objects of class basic_string<charT,traits,Allocator>

wstreambuf

Abstract base class for deriving various stream buffers to facilitate control of character sequences 

wstring

A typedef for basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t>>

wstringbuf

Associates the input or output sequence with a sequence of arbitrary characters 

13.3 STLport

Use the STLport implementation of the standard library if you wish to use an alternative standard library to libCstd. You can issue the following compiler option to turn off libCstd and use the STLport library instead:

See A.2.49 -library=l[,l...] for more information.

This release includes both a static archive called libstlport.a and a dynamic library called libstlport.so.

Consider the following information before you decide whether or not you are going to use the STLport implementation:

13.3.1 Redistribution and Supported STLport Libraries

See the Runtime Libraries Readme for a list of libraries and object files that you can redistribute with your executables or libraries under the terms of the End User Object Code License. The C++ section of this readme lists which version of the STLport .so this release of the compiler supports. This readme is available as part of the installed product. To view the HTML version of this readme, point your browser to the default installation directory:

     file:/opt/SUNWspro/docs/index.html

Note –

If your product software is not installed in the default directory, ask your system administrator for the equivalent path on your system.


The following test case does not compile with STLport because the code in the test case makes unportable assumptions about the library implementation. In particular, it assumes that either <vector> or <iostream> automatically include <iterator>, which is not a valid assumption.


#include <vector>
#include <iostream>

using namespace std;

int main ()
{
    vector <int> v1 (10);
    vector <int> v3 (v1.size());
    for (int i = 0; i < v1.size (); i++)
      {v1[i] = i; v3[i] = i;}
    vector <int> v2(v1.size ());
    copy_backward (v1.begin (), v1.end (), v2.end ());
    ostream_iterator<int> iter (cout, " ");
    copy (v2.begin (), v2.end (), iter);
    cout << endl;
    return 0;
}

To fix the problem, include <iterator> in the source.