©Copyright 1996 Rogue Wave Software If you are accessing this for the first time, please read the licensing statement. Standard C++ Library also has a User Guide. Standard C++ Library Class Reference Version 1.2 Introduction Standards Conformance Contents Introduction This reference guide is an alphabetical listing of all of the classes, algorithms, and function objects provided by this release of Rogue Wave's Standard C++ Library. The gray band on the first page of each entry indicates the category (e.
Algorithms #include Complex Number Library adjacent_find binary_search copy copy_backward count count_if equal equal_range fill fill_n find find_end find_first_of find_if for_each generate generate_n includes inplace_merge iter_swap lexicographical_compare lower_bound make_heap max max_element merge min min_element mismatch next_permutation nth_element partial_sort partial_sort_copy partition pop_heap prev_permutation push_heap random_shuffle remove remove_copy remove_copy_if remove_if replace
Insert Iterators #include Iterators back_insert_iterator back_inserter front_insert_iterator front_inserter insert_iterator inserter #include bidirectional iterator forward iterator input iterator output iterator random access iterator reverse_bidirectional_iterator reverse_iterator Iterator operations advance distance #include Memory Handling Primitives get_temporary_buffer return_temporary_buffer #include Memory Management #include Numeric Limits
● Algorithms ● allocator ● Associative Containers ● auto_ptr ● back_insert_iterator, back_inserter ● basic_string ● Bidirectional Iterators ● binary_function ● binary_negate ● binary_search ● bind1st, bind2nd, binder1st, binder2nd ● bitset ● complex ● complex ● Containers ● copy, copy_backward ● count, count_if ● deque ● distance ● distance_type ● divides ● equal ● equal_range ● equal_to ● exception ● fill, fill_n ● find ● find_end ● find_first_of ●
● Function Objects ● generate, generate_n ● get_temporary_buffer ● greater ● greater_equal ● Heap Operations ● includes ● inner_product ● inplace_merge ● Input Iterators ● Insert Iterators ● insert_iterator, inserter ● istream_iterator ● iterator_category ● Iterators ● iter_swap ● less ● less_equal ● lexicographical_compare ● limits ● list ● logical_and ● logical_not ● logical_or ● lower_bound ● make_heap ● map ● max ● max_element ● merge ● min ●
● mismatch ● modulus ● multimap ● multiset ● negate ● Negators ● next_permutation ● not1 ● not2 ● not_equal_to ● nth_element ● numeric_limits ● operator!=, operator>, operator<=, operator>= ● ostream_iterator ● Output Iterators ● pair ● partial_sort ● partial_sort_copy ● partial_sum ● partition ● permutation ● plus ● pointer_to_binary_function ● pointer_to_unary_function ● pop_heap ● Predicates ● prev_permutation ● priority_queue ● ptr_fun ● push_he
● raw_storage_iterator ● remove ● remove_copy ● remove_copy_if ● remove_if ● replace ● replace_copy ● replace_copy_if ● replace_if ● return_temporary_buffer ● reverse ● reverse_bidirectional_iterator, reverse_iterator ● reverse_copy ● reverse_iterator ● rotate, rotate_copy ● search, search_n ● Sequences ● set ● set_difference ● set_intersection ● set_symmetric_difference ● set_union ● sort ● sort_heap ● stable_partition ● stable_sort ● stack ● Stream It
● transform ● unary_function ● unary_negate ● uninitialized_copy ● uninitialized_fill ● uninitialized_fill_n ● unique, unique_copy ● upper_bound ● value_type ● vector ● wstring
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software accumulate Generalized Numeric Operation Summary Accumulate all elements within a range into a single value.
Description accumulate applies a binary operation to init and each value in the range [first,last). The result of each operation is returned in init. This process aggregates the result of performing the operation on every element of the sequence into a single value. Accumulation is done by initializing the accumulator acc with the initial value init and then modifying it with acc = acc + *i or acc = binary_op(acc, *i) for every iterator i in the range [first, last) in order.
for(iterator i = v1.begin(); i != v1.end(); i++) cout << *i << " "; cout << " where N = 10." << endl; cout << "The sum = (N*N + N)/2 = " << sum << endl; cout << "The product = N! = " << prod << endl; return 0; } Output : For the series: 1 2 3 4 5 6 7 8 9 10 The sum = (N*N + N)/2 = 55 The product = N! = 3628800 where N = 10. Warnings If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software adjacent_difference Generalized Numeric Operation Summary Outputs a sequence of the differences between each adjacent pair of elements in a range.
binary_op (*(first + (i - result)), *(first + (i - result) - 1)) result is assigned the value of *first. adjacent_difference returns result + (last - first). result can be equal to first. This allows you to place the results of applying adjacent_difference into the original sequence. Complexity This algorithm performs exactly (last-first) - 1 applications of the default operation (-) or binary_op. Example // // adj_diff.
The differences 1 0 1 1 2 3 The products of 1 1 2 6 15 between adjacent elements are: 5 8 13 21 adjacent elements are: 40 104 273 714 1870 Warning If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software adjacent_find Algorithm Summary Find the first adjacent pair of elements in a sequence that are equivalent.
Description There are two versions of the adjacent_find algorithm. The first finds equal adjacent elements in the sequence defined by iterators first and last and returns an iterator i pointing to the first of the equal elements. The second version lets you specify your own binary function to test for a condition. It returns an iterator i pointing to the first of the pair of elements that meet the conditions of the binary function.
<< *it4 << endl; return 0; } Output : 3 3 2 2 Warning If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software advance Iterator Operation Summary Move an iterator forward or backward (if available) by a certain distance.
decrements reference i. Remember that advance accepts a negative argument n for random access and bidirectional iterators only. Example // // advance.cpp // #include #include #include int main() { // //Initialize a list using an array // int arr[6] = {3,4,5,6,7,8}; list l(arr,arr+6); // //Declare a list iterator, s.b. a ForwardIterator // list::iterator itr = l.begin(); // //Output the original list // cout << "For the list: "; copy(l.begin(),l.
Warnings If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Algorithms Summary Generic algorithms for performing various operations on containers and sequences. Contents ● Synopsis ● Description ● Algorithms by Mutating/Non-mutating Function ● Algorithms by Operation ● Algorithms by Iterator Category ● Complexity ● See Also Synopsis #include The synopsis of each algorithm appears in its entry in the reference guide.
uses In addition to requiring certain iterator capabilities, algorithms may require a container to be in a specific state. For example, some algorithms can only work on previously sorted containers. Because most algorithms rely on iterators to gain access to data, they can be grouped according to the type of iterator they require, as is done in the Algorithms by Iterator section below. They can also be grouped according to the type of operation they perform.
partial_sort partial_sort_copy partition prev_permutation push_heap pop_heap random_shuffle remove remove_copy remove_copy_if set_union sort sort_heap stable_partition stable_sort swap swap_ranges transform unique unique_copy Note that the library provides both in place and copy versions of many algorithms, such as replace and replace_copy. The library also provides versions of algorithms that allow the use of default comparators and comparators supplied by the user.
copy copy_backward Transforming operations partition random_shuffle replace replace_copy replace_copy_if replace_if reverse reverse_copy rotate rotate_copy stable_partition transform Swap operations swap swap_ranges Scanning operations accumulate for_each Remove operations remove remove_copy remove_copy_if remove_if unique unique_copy Sorting operations nth_element partial_sort partial_sort_copy sort stable_sort Merge operations (Elements must be sorted) inplace_merge merge Set operations (Eleme
Algorithms by Iterator Category Each algorithm requires certain kinds of iterators (for a description of the iterators and their capabilities see the Iterators entry in this manual). The following set of lists groups the algorithms according to the types of iterators they require.
stable_permutation Algorithms that read from bidirectional iterators and write to output iterators: reverse_copy Algorithms that require random access iterators: make_heap pop_heap nth_element push_heap partial_sort random_shuffle sort sort_heap stable_sort Algorithms that read from input iterators and write to random access iterators: partial_sort_copy Complexity The complexity for each of these algorithms is given in the manual page for that algorithm.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software allocator Summary The default allocator object for storage management in Standard Library containers.
interface, we recommend that you support the default interface as well, since that is the only way to ensure long-term portability. See the User's Guide section on building containers for an explanation of how to support both the standard and the alternate allocator interfaces. A generic allocator must be able to allocate space for objects of arbitrary type, and it must be able to construct those objects on that space.
template typename types::pointer allocate (size_type,typename types::const_pointer = 0); template void deallocate( typename types::pointer); template size_type max_size () const; template void construct (T1*, const T2&); template void destroy (T*) }; // specialization class allocator::types { typedef void* pointer; typedef const void* const_pointer; typedef void value_type; }; // globals inline void * operator new (size_t, al
template typename types::pointer allocate (size_type n, typename types::const_pointer p = 0) Allocate storage. Returns a pointer to the first element in a block of storage n*sizeof(T) bytes in size. The block will be aligned appropriately for objects of type T. Throws the exception bad_alloc if the storage is unavailable. This function uses operator new(size_t).
void destroy (T*); }; // // Specialization // class allocator_interface { typedef void* pointer ; typedef const void* const_pointer ; }; Alternate Allocator Description The description for the operations of allocator_interface are the same as for corresponding operations of the standard allocator, except that allocator_interface members allocate and deallocate call respective functions in allocator , which are in turn implemented as are the standard allocator functions.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Associative Containers Summary Associative containers are ordered containers. These containers provide member functions that allow the efficient insertion, retrieval and manipulation of keys. The standard library provides the map, multimap, set and multiset associative containers. map and multimap associate values with the keys and allow for fast retrieval of the value, based upon fast retrieval of the key.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software auto_ptr Memory Management Summary A simple, smart pointer class.
Interface template class auto_ptr { public: // constructor/copy/destroy explicit auto_ptr (X* = 0); auto_ptr (const auto_ptr&); void operator= (const auto_ptr&); ~auto_ptr (); // members X& operator* () const; X* operator-> () const; X* get () const; X* release (); void reset (X* = 0); }; Constructors and Destructors explicit auto_ptr (X* p = 0); Constructs an object of class auto_ptr, initializing the held pointer to p.
X* operator-> () const; Returns the underlying pointer. Member Functions X* get () const; Returns the underlying pointer. X* release(); Releases ownership of the underlying pointer. Returns that pointer. void reset (X* p = 0); Requires that p points to an object of class X or a class derived from X for which delete p is defined and accessible, or p is a null pointer. Deletes the current underlying pointer, then resets it to p. Example // // auto_ptr.cpp // #include
// auto_ptr a = b; // // Output the value contained by the underlying pointer. // cout << a->get() << endl; // // The pointer will be deleted when a is destroyed on // leaving scope.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software back_insert_iterator, back_inserter Insert Iterator Summary An insert iterator used to insert items at the end of a collection.
Description Insert iterators let you insert new elements into a collection rather than copy a new element's value over the value of an existing element. The class back_insert_iterator is used to insert items at the end of a collection. The function back_inserter creates an instance of a back_insert_iterator for a particular collection type. A back_insert_iterator can be used with vectors, deques, and lists, but not with maps or sets.
Increments the input iterator and returns *this. Helper Function template back_insert_iterator back_inserter (Container& x) Returns a back_insert_iterator that will insert elements at the end of container x. This function allows you to create insert iterators inline. Example // // ins_itr.cpp // #include #include #include int main () { // // Initialize a deque using an array.
deque d2(4, 1); // // Insert d2 at front of d. // copy(d2.begin(), d2.end(), front_inserter(d)); // // Output the new deque. // cout << endl << endl; cout << "Use a front_inserter: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // Insert d2 at back of d. // copy(d2.begin(), d2.end(), back_inserter(d)); // // Output the new deque. // cout << endl << endl; cout << "Use a back_inserter: " << endl << " "; copy(d.begin(), d.
See Also Insert Iterators
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software basic_string Strings Library Summary A templated class for handling sequences of character-like entities. string and wstring are specialized versions of basic_string for chars and wchar_ts, respectively.
Interface template , class Allocator = allocator> class basic_string { public: // Types typedef traits traits_type; typedef typename traits::char_type value_type; typedef Allocator allocator_type; typename size_type; typename difference_type; typename reference; typename const_reference; typename pointer; typename const_pointer; typename iterator; typename const_iterator; typename const_reverse_iterator; typename reverse_iterator; static const size_type
reference operator[](size_type); const_reference at(size_type) const; reference at(size_type); // Modifiers basic_string& operator+=(const basic_string&); basic_string& operator+=(const charT*); basic_string& operator+=(charT); basic_string& append(const basic_string&); basic_string& append(const basic_string&, size_type, size_type); basic_string& append(const charT*, size_type); basic_string& append(const charT*); basic_string& append(size_type, charT); template basic_string& append(In
template basic_string& replace(iterator, iterator, InputIterator, InputIterator); size_type copy(charT*, size_type, size_type = 0); void swap(basic_string&); // String operations const charT* c_str() const; const charT* data() const; const allocator_type& get_allocator() const; size_type find(const basic_string&, size_type = 0) const; size_type find(const charT*, size_type, size_type) const; size_type find(const charT*, size_type = 0) const; size_type find(char
template basic_string operator+ (const basic_string&, const basic_string&); template basic_string operator+ (const charT*, const basic_string&); template basic_string operator+ (charT, const basic_string&); template basic_string operator+ (const basic_string&, const charT*); template ba
Constructors and Destructors In all cases, the Allocator parameter will be used for storage management. explicit basic_string (const Allocator& a = Allocator()); The default constructor. Creates a basic_string with the following effects: data() a non-null pointer that is copyable and can have 0 added to it size() 0 capacity() an unspecified value basic_string (const basic_string& str); Copy constructor. Creates a string that is a copy of str.
capacity() a value at least as large as size() template basic_string (InputIterator first, InputIterator last, const Allocator& a = Allocator()); Creates a basic_string of length last - first, filled with all values obtained by dereferencing the InputIterators on the range [first, last).
Iterators iterator begin (); const_iterator begin () const; Return an iterator initialized to the first element of the string. iterator end (); const_iterator end () const; Return an iterator initialized to the position after the last element of the string. reverse_iterator rbegin (); const_reverse_iterator rbegin () const; Returns an iterator equivalent to reverse_iterator(end()). reverse_iterator rend (); const_reverse_iterator rend () const; Returns an iterator equivalent to reverse_iterator(begin()).
template basic_string& assign (InputIterator first, InputIterator last); Replace the value of this string with the value of another. All versions of the function assign values to this string. The first two variations assign the lesser of n and s.size() - pos characters of s, beginning at position pos. The second variation throws an out_of_range exception if pos > str.size(). The third version of the function assigns n characters of the array pointed to by s.
c_str () const; const charT* data () const; Return a pointer to the initial element of an array whose first size() elements are copies of the elements in this string. A traits::eos() element is appended to the end. The elements of the array may not be altered, and the returned pointer is only valid until a non-const member function of this string is called. If size() is zero, the data() function returns a NULL pointer. bool empty () const; Returns size() == 0.
find_first_not_of(basic_string(s,n), pos) find_first_not_of(basic_string(s), pos) find_first_not_of(basic_string(1, c), pos) size_type find_first_of (const basic_string& str, size_type pos = 0) const; Searches for the first occurence at or after position pos of any element of str in this string. If found, the index of this matching character is returned. If not found, npos is returned. Equality is defined by traits::eq().
find_last_of(basic_string(s), pos) find_last_of(basic_string(1, c), pos) basic_string& insert (size_type pos1, const basic_string& s); basic_string& insert (size_type pos, const basic_string& s, size_type pos2 = 0, size_type n = npos); basic_string& insert (size_type pos, const charT* s, size_type n); basic_string& insert (size_type pos, const charT* s); basic_string& insert (size_type pos, size_type n, charT c); Insert additional elements at position pos in this string.
rfind(basic_string(1, c), pos) basic_string& replace (size_type pos, size_type n1, const basic_string& s); basic_string& replace (size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2); basic_string& replace (size_type pos, size_type n1, const charT* s, size_type n2); basic_string& replace (size_type pos, size_type n1, const charT* s); basic_string& replace (size_type pos, size_type n1, size_type n2, charT c); The replace function replaces selected elements of this string with
size () const; Return the number of elements contained in this string. basic_string substr (size_type pos = 0, size_type n = npos) const; Returns a string composed of copies of the lesser of n and size() characters in this string starting at index pos. Throws an out_of_range exception if pos <= size(). void swap (basic_string& s); Swaps the contents of this string with the contents of s.
const basic_string& rhs); Returns a boolean value representing the inequality of lhs and rhs. Inequality is defined by the compare() member function. template bool operator!= (const charT* lhs, const basic_string& rhs); template bool operator!= (const basic_string& lhs, const charT* rhs); Returns a boolean value representing the inequality of lhs and rhs. Inequality is defined by the compare() member function.
operator<= (const charT* lhs, const basic_string& rhs); template bool operator<= (const basic_string& lhs, const charT* rhs); Returns a boolean value representing the lexigraphical less-than-or-equal relationship of lhs and rhs. Less-than-or-equal is defined by the compare() member function.
while(test.empty() || test.size() <= 5) { cout << "Type a string between 5 and 100 characters long. " << endl; cin >> test; } //Test operator[] access cout << "Changing the third character from " << test[2] << " to * " << endl; test[2] = '*'; cout << "now its: " << test << endl << endl; //Try the insertion member function cout << "Identifying the middle: "; test.insert(test.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Bidirectional Iterators Iterator Summary An iterator that can both read and write and can traverse a container in both directions Contents ● Description ● Key to Iterator Requirements ● Requirements for Bidirectional Iterators ● See Also Description For a complete discussion of iterators, see the Iterators section of this reference.
r value of type X& t value of type T Requirements for Bidirectional Iterators A bidirectional iterator must meet all the requirements listed below. Note that most of these requirements are also the requirements for forward iterators. Xu u might have a singular value X() X() might be singular X(a) copy constructor, a == X(a). X u(a) copy constructor, u == a Xu=a assignment, u == a a == b, a != b return value convertable to bool a->m equivalent to (*a).
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software binary_function Function Object Summary Base class for creating binary function objects.
objects are required to provide the typedefs first_argument_type, second_argument_type, and result_type. The binary_function class makes the task of creating templated binary function objects easier by providing the necessary typedefs for a binary function object. You can create your own binary function objects by inheriting from binary_function. See Also Function Objects, unary_function, the Function Objects section of the User's Guide.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software binary_negate Function Object Summary Function object that returns the complement of the result of its binary predicate Contents ● Synopsis ● Description ● Interface ● Constructor ● Operator ● See Also Synopsis #include template class binary_negate ; Description binary_negate is a function object class that provides a return type for the function adaptor not2.
Interface template class binary_negate : public binary_function { public: typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; ty
See Also binary_function, not2, unary_negate
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software binary_search Algorithm Summary Performs a binary search for a value on a container.
Description The binary_search algorithm, like other related algorithms (equal_range, lower_bound and upper_bound) performs a binary search on ordered containers. All binary search algorithms have two versions. The first version uses the less than operator (operator <) to perform the comparison, and assumes that the sequence has been sorted using that operator. The second version allows you to include a function object of type Compare, which it assumes was the function used to sort the sequence.
bool b2 = binary_search(v1.begin(),v1.end(),11,less()); // // Output results // cout << "In the vector: "; copy(v1.begin(),v1.
Click on the banner to return to the Class Reference home page.
Description Because so many functions provided by the standard library take other functions as arguments, the library includes classes that let you build new function objects out of old ones. Both bind1st() and bind2nd() are functions that take as arguments a binary function object f and a value x, and return, respectively, classes binder1st and binder2nd. The underlying function object must be a subclass of binary_function.
typename Operation::result_type> { public: typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; binder2nd(const Operation&, const typename Operation::second_argument_type&); result_type operator() (const argument_type&) const; }; // Creator bind1st template binder1st
// // Now use this new predicate in a call to find_if // iterator it1 = find_if(v1.begin(),v1.end(),equal_to_3); // // Even better, construct the new predicate on the fly // iterator it2 = find_if(v1.begin(),v1.end(),bind1st(equal_to(),3)); // // And now the same thing using bind2nd // Same result since == is commutative // iterator it3 = find_if(v1.begin(),v1.end(),bind2nd(equal_to(),3)); // // it3 = v1.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software bitset Container Summary A template class and related functions for storing and manipulating fixed-size sequences of bits.
Interface template class bitset { public: // bit reference: class reference { friend class bitset; public: ~reference(); reference& operator= (bool); reference& operator= (const reference&); bool operator~() const; operator bool() const; reference& flip(); }; // Constructors bitset (); bitset (unsigned long); explicit bitset (const string&, size_t = 0, size_t = (size_t)-1); bitset (const bitset&); bitset& operator= (const bitset&); // Bitwise Operators and Bitwise Operator Assignment
template ostream& operator<< (ostream&, const bitset&); Constructors bitset(); Constructs an object of class bitset, initializing all bit values to zero. bitset(unsigned long val); Constructs an object of class bitset, initializing the first M bit values to the corresponding bits in val. M is the smaller of N and the value CHAR_BIT * sizeof(unsigned long). If M < N, remaining bit positions are initialized to zero. Note: CHAR_BIT is defined in .
Replaces each bit at position I with 0 if I < pos or with the value of the bit at I - pos if I >= pos. Returns *this. bitset& operator>>= (size_t pos); Replaces each bit at position I with 0 if pos >= N-I or with the value of the bit at position I + pos if pos < N-I. Returns *this. bitset& operator>> (size_t pos) const; Returns bitset(*this) >>= pos. bitset& operator<< (size_t pos) const; Returns bitset(*this) <<= pos.
count () const; Returns a count of the number of bits set in *this. bitset& flip(); Flips all bits in *this, and returns *this. bitset& flip (size_t pos); Flips the bit at position pos in *this and returns *this. Throws an out_of_range exception if pos does not correspond to a valid bit position. bool none () const; Returns true if no bit in *this is set. Otherwise returns false. bitset& reset(); Resets all bits in *this, and returns *this.
See Also Containers
Click on the banner to return to the Class Reference home page.
Synopsis #include template class complex ; Description complex is a class that supports complex numbers. A complex number has a real part and an imaginary part. The complex class supports equality, comparison and basic arithmetic operations. In addition, mathematical functions such as exponentiation, logarithmic, power, and square root are also available.
template complex operator- (const complex&, T); template complex operator- (T, const complex&); template complex operator* (const complex&, const complex&); template complex operator* (const complex&, T); template complex operator* (T, const complex&); template complex operator/ (const complex&, const complex&); template complex operator/ (const complex&, T); template complex operator/ (
template T> T> T> complex complex complex complex template T> T> T> T> T> T> T> T> T> complex complex complex complex complex complex complex complex complex complex template T> T>
Adds c to itself, then returns the result. template complex operator-= (const complex& c); Subtracts c from itself, then returns the result. template complex operator*= (const complex& c); Multiplies itelf by c then returns the result. template complex operator/= (const complex& c); Divides itself by c, then returns the result. Member Functions T imag() const; Returns the imaginary part of the complex number.
template complex operator* (const complex& lhs,const complex& rhs); template complex operator* (const complex& lhs, T rhs); template complex operator* (T lhs, const complex& rhs); Returns the product of lhs and rhs.
operator!= (T x, const complex& y); Returns true if x is not equal to the real part of y or the imaginary part of y is not equal to 0. template istream& operator>> (istream& is, complex& x); Reads a complex number x into the input stream is. x may be of the form u, (u), or (u,v) where u is the real part and v is the imaginary part. If bad input is encountered, the ios::badbit flag is set. template ostream& operator<< (ostream& os, const complex& x); Returns os << "(" << x.
atan2 (const complex& a, const complex& b); Returns the arctangent of a/b. template complex conj (const complex& c); Returns the conjugate of c. template complex cos (const complex& c); Returns the cosine of c. template complex cosh (const complex& c); Returns the hyperbolic cosine of c. template complex exp (const complex& x); Returns e raised to the x power.
pow (const complex& x, const complex& y); template complex pow (T x, const complex& y); Returns x raised to the y power. template T real (const complex& c); Returns the real part of c. template complex sin (const complex& c); Returns the sine of c. template complex sinh (const complex& c); Returns the hyperbolic sine of c. template complex sqrt (const complex& x); Returns the square root of x.
} Output : a = (1.42804e-06,-0.0002873), b = (58.2199,69.7354) Warnings On compilers that don't support member function templates, the arithmetic operators will not work on any arbitrary type. (They will work only on float, double and long doubles.) You also will only be able to perform binary arithmetic on types that are the same. Compilers that don't support non-converting constructors will permit unsafe downcasts (i.e., long double to double, double to float, long double to float).
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Containers Summary A standard template library (STL) collection. Contents ● Description ● Container Requirements ● Reversible Containers ● Sequences ● Associative Containers ● See Also Description Within the standard template library, collection classes are often described as containers.
● A container allocates all storage for the objects it holds. ● A container X of objects of type T provides the following types: X::value_type aT X::reference lvalue of T X::const_reference const lvalue of T X::iterator an iterator type pointing to T. X::iterator cannot be an output iterator. X::const_iterator an iterator type pointing to const T. x::iterator cannot be an output iterator.
X::const_reverse_iterator An iterator type pointing to const T ● A reversible container provides the following member functions: rbegin() Returns a reverse_iterator or a const_reverse_iterator pointing past the end of the collection rend() Returns a reverse_iterator or a const_reverse_iterator pointing to the first element in the collection.
Associative Containers In addition to the requirements for a container, the following requirements hold for associative containers: ● For an associative container iterator and const_iterator must be bidirectional iterators. Associative containers are inherently sorted. Their iterators proceed through the container in the non-descending order of keys (where non-descending order is defined by the comparison object that was used to construct the container).
insert(p,t) If the container does not support redundant key values then this function only inserts t if there is no key present that is equal to the key of t. If the container does support redundant keys then this function always inserts the element t. The iterator p serves as a hint of where to start searching, allowing for some optimization of the insertion. It does not restrict the algorithm from inserting ahead of that location if necessary. insert(i,j) Inserts elements from the range [i,j).
Click on the banner to return to the Class Reference home page.
Unless result is an insert iterator, copy assumes that at least as many elements follow result as are in the range [first, last). The copy_backward algorithm copies elements in the range specified by [first, last) into the range specified by [result - (last - first), result), starting from the end of the sequence (last-1) and progressing to the front (first). Note that copy_backward does not reverse the order of the elements, it simply reverses the order of transfer.
copy(v1.begin(),v1.end(),back_inserter(v4)); // // Copy all four to cout // ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; copy(v4.begin(),v4.end(),out); cout << endl; return 0; } Output : 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Warning If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software count, count_if Algorithm Summary Count the number of elements in a container that satisfy a given condition.
*i == value The count_if algorithm lets you specify a predicate, and increments n each time an element in the sequence satisfies the predicate. That is, count_if adds to n the number of iterators i in the range [first, last) for which the following condition holds: pred(*i) == true. Complexity Both count and count_if perform exactly last-first applications of the corresponding predicate. Example // // count.cpp // #include #include #include
instead of: vector
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software deque Container Summary A sequence that supports random access iterators and efficient insertion/deletion at both beginning and end.
Description deque is a type of sequence that supports random access iterators. It supports constant time insert and erase operations at the beginning or the end of the container. Insertion and erase in the middle take linear time. Storage management is handled by the Allocator template parameter.
deque& operator= (const deque&); template void assign (InputIterator, InputIterator); template void assign (Size); template void assign (Size, const T&); allocator_type get allocator () const; // Iterators iterator begin (); const_iterator begin () const; iterator end (); const_iterator end () const; reverse_iterator rbegin (); const_reverse_iterator rbegin () const; reverse_iterator rend (); const_reverse_iterator r
void clear(); }; // Non-member Operators template bool operator== (const deque&, const deque&); template bool operator< (const deque&, const deque&); // Specialized Algorithms template voice swap (deque&, deque&); Constructors and Destructor explicit deque (const Allocator& alloc = Allocator()); The default constructor.
Allocator allocator allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management. Iterators iterator begin (); Returns a random access iterator that points to the first element. const_iterator begin () const; Returns a constant random access iterator that points to the first element. iterator end (); Returns a random access iterator that points to the past-the-end value.
must be between 0 and the size less one. const_reference operator[] (size_type n) const; Returns a constant reference to element n of self. The index n must be between 0 and the size() - 1. Member Functions template void assign (InputIterator first, InputIterator last); Erases all elements contained in self, then inserts new elements from the range [first, last).
Erases all elements from the self. bool empty () const; Returns true if the size of self is zero. reference front (); Returns a reference to the first element. const_reference front () const; Returns a constant reference to the first element. iterator erase (iterator first, iterator last); Deletes the elements in the range (first, last). Returns an iterator pointing to the element following the last deleted element, or end() if there were no elements after the deleted range.
Returns size() of the largest possible deque. void pop_back (); Removes the last element. Note that this function does not return the element. void pop_front (); Removes the first element. Note that this function does not return the element void push_back (const T& x); Appends a copy of x to the end. void push_front (const T& x); Inserts a copy of x at the front. void resize (size_type sz); Alters the size of self.
Equality operator. Returns true if x is the same as y. template bool operator< (const deque& x, const deque& y); Returns true if the elements contained in x are lexicographically less than the elements contained in y. template void swap (deque& a, deque& b); Efficiently swaps the contents of a and b. Example // // deque.
} int main() { play_poker(); print_current_hand(current_hand.begin(),current_hand.end()); return 0; } Output : aceofspades kingofspades queenofspades jackofspades tenofspades Warnings Member function templates are used in all containers provided by the Standard Template Library. An example of this is the constructor for deque that takes two templated iterators: template deque (InputIterator, InputIterator); deque also has an insert function of this type.
instead of: deque
Click on the banner to return to the Class Reference home page.
Example // // distance.cpp // #include #include #include int main() { // //Initialize a vector using an array // int arr[6] = {3,4,5,6,7,8}; vector v(arr,arr+6); // //Declare a list iterator, s.b. a ForwardIterator // vector::iterator itr = v.begin()+3; // //Output the original vector // cout << "For the vector: "; copy(v.begin(),v.
Warning If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software distance_type Iterator primitive Summary Determine the type of distance used by an iterator.
Description The distance_type family of function templates return a pointer to a value that is of the same type as that used to represent a distance between two iterators. The first four of these take an iterator of a particular type and return a pointer to a default value of the distance_type for that iterator. The T* form of the function returns ptrdiff_t*. Generic algorithms use this function to create local variables of the correct type.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software divides Function Object Summary Returns the result of dividing its first argument by its second. Contents ● Synopsis ● Description ● Interface ● See Also Synopsis #include template struct divides; Description divides is a binary function object. Its operator() returns the result of dividing x by y.
Interface template struct divides : binary_function { typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; T operator() (const T&, const T&) const; }; See Also binary_function, Function Objects
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software equal Algorithm Summary Compares two ranges for equality.
predicate as the comparison function. The first version returns true if all of the corresponding elements are equal to each other. The second version of equal returns true if for each pair of elements in the two ranges, the result of applying the binary predicate is true. In other words, equal returns true if both of the following are true: 1. There are at least as many elements in the second range as in the first; 2.
return 0; } Output : FALSE FALSE Warnings If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software equal_range Algorithm Summary Find the largest subrange in a collection into which a given value can be inserted without violating the ordering of the collection.
Description The equal_range algorithm performs a binary search on an ordered container to determine where the element value can be inserted without violating the container's ordering. The library provides two versions of the algorithm. The first version uses the less than operator (operator <) to search for the valid insertion range, and assumes that the sequence was sorted using the less than operator.
// // Try equal_range variants // pair p1 = equal_range(v1.begin(),v1.end(),3); // p1 = (v1.begin() + 4,v1.begin() + 5) pair p2 = equal_range(v1.begin(),v1.end(),2,less()); // p2 = (v1.begin() + 4,v1.begin() + 5) // Output results cout << endl << "The equal range for 3 is: " << "( " << *p1.first << " , " << *p1.second << " ) " << endl << endl; cout << endl << "The equal range for 2 is: " << "( " << *p2.first << " , " << *p2.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software equal_to Function Object Summary Binary function object that returns true if its first argument equals its second Contents ● Synopsis ● Description ● Interface ● See Also Synopsis #include template struct equal_to; Description equal_to is a binary function object. Its operator() returns true if x is equal to y.
equal_to()); After this call to transform, vecResult(n) will contain a "1" if vec1(n) was equal to vec2(n) or a "0" if vec1(n) was not equal to vec2(n).
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software exception Standard Exception Summary Classes supporting logic and runtime errors.
Interface class exception { public: exception () throw(); exception (const exception&) throw(); exception& operator= (const exception&) throw(); virtual ~exception () throw(); virtual const char* what () const throw(); }; class logic_error : public exception { public: logic_error (const string& what_arg); }; class domain_error : public logic_error { public: domain_error (const string& what_arg); }; class invalid_argument : public logic_error { public: invalid_argument (const string& what_arg); }; class leng
Constructors exception () throw(); Constructs an object of class exception. exception (const exception&) throw(); The copy constructor. Copies an exception object. Destructor virtual ~exception() throw(); Destroys an object of class exception. Operators exception& operator= (const exception&) throw(); The assignment operator. Copies an exception object.
Constructs an object of class out_of_range. runtime_error::runtime_error (const string& what_arg); Constructs an object of class runtime_error. range_error::range_error (const string& what_arg); Constructs an object of class range_error. overflow_error::overflow_error (const string& what_arg); Constructs an object of class overflow_error. Example // // exception.cpp // #include
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software fill, fill_n Algorithm Summary Initializes a range with a given value.
insert iterator. Complexity fill makes exactly last - first assignments, and fill_n makes exactly n assignments. Example // // fill.cpp // #include #include #include int main() { int d1[4] = {1,2,3,4}; // // Set up two vectors // vector v1(d1,d1 + 4), v2(d1,d1 + 4); // // Set up one empty vector // vector v3; // // Fill all of v1 with 9 // fill(v1.begin(),v1.end(),9); // // Fill first 3 of v2 with 7 // fill_n(v2.
copy(v3.begin(),v3.end(),out); cout << endl; // // Fill cout with 3 5's // fill_n(ostream_iterator(cout," "),3,5); cout << endl; return 0; } Output : 9 9 9 9 7 7 7 4 11 11 11 11 11 5 5 5 Warnings If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software find Algorithm Summary Find an occurence of value in a sequence Contents ● Synopsis ● Description ● Complexity ● Example ● Warning ● See Also Synopsis #include template InputIterator find(InputIterator first, InputIterator last, const T& value); Description The find algorithm lets you search for the first occurence of a particular value in a sequence.
Complexity find peforms at most last-first comparisons. Example // // find.cpp // #include #include int main() { typedef vector::iterator iterator; int d1[10] = {0,1,2,2,3,4,2,2,6,7}; // Set up a vector vector v1(d1,d1 + 10); // Try find iterator it1 = find(v1.begin(),v1.end(),3); // it1 = v1.begin() + 4; // Try find_if iterator it2 = find_if(v1.begin(),v1.end(),bind1st(equal_to(),3)); // it2 = v1.
vector See Also adjacent_find, find_first_of, find_if
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software find_end Algorithm Summary Finds a subsequence of equal values in a sequence.
Description The find_end algorithm finds the last occurrence of a subsequence, indicated by [first2, last2), in a sequence, [first1,last1). The algorithm returns an iterator pointing to the first element of the found subsequence, or last1 if no match is found.
// Try both find_end variants. // iterator it3 = find_end (v1.begin(), v1.end(), v2.begin(), v2.end()); iterator it4 = find_end (v1.begin(), v1.end(), v2.begin(), v2.end(), equal_to()); // // Output results of find_first_of. // Iterator now points to the first element that matches one of // a set of values // cout << "For the vectors: "; copy (v1.begin(), v1.end(), ostream_iterator(cout," ")); cout << " and "; copy (v2.begin(), v2.
See Also Algorithms, find, find_if, adjacent_find
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software find_first_of Algorithm Summary Finds the first occurrence of any value from one sequence in another sequence.
BinaryPredicate pred); Description The find_first_of algorithm finds a the first occurrence of a value from a sequence, specified by first2, last2, in a sequence specified by first1, last1. The algorithm returns an iterator in the range [first1, last1) that points to the first matching element. If the first sequence [first1, last1) does not contain any of the values in the second sequence, find_first_of returns last1.
equal_to()); // // Output results // cout << "For the vectors: "; copy(v1.begin(),v1.end(), ostream_iterator(cout," " )); cout << " and "; copy(v2.begin(),v2.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software find_if Algorithm Summary Find an occurrence of value in a sequence that satisfies a specifed predicate.
pred(*i) == true. If no such iterator is found, find_if returns last. Complexity find_if performs at most last-first applications of the corresponding predicate. Example // // find.cpp // #include #include #include int main() { typedef vector::iterator iterator; int d1[10] = {0,1,2,2,3,4,2,2,6,7}; // Set up a vector vector v1(d1,d1 + 10); // Try find iterator it1 = find(v1.begin(),v1.end(),3); // it1 = v1.begin() + 4; // Try find_if iterator it2 = find_if(v1.
Warning If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software for_each Algorithm Summary Applies a function to each element in a range.
Complexity The function f is applied exactly last - first times. Example // // for_each.cpp // #include #include #include
See Also Algorithms, Function Objects
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Forward Iterators Iterator Summary A forward-moving iterator that can both read and write. Contents ● Description ● Key to Iterator Requirements ● Requirements for Forward Iterators ● See Also Description For a complete discussion of iterators, see the Iterators section of this reference.
r value of type X& t value of type T Requirements for Forward Iterators The following expressions must be valid for forward iterators: Xu u might have a singular value X() X() might be singular X(a) copy constructor, a == X(a). X u(a) copy constructor, u == a Xu=a assignment, u == a a == b, a != b return value convertible to bool *a return value convertible to T& a->m equivalent to (*a).
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software front_insert_iterator, front_inserter Insert Iterator Summary An insert iterator used to insert items at the beginning of a collection.
Description Insert iterators let you insert new elements into a collection rather than copy a new element's value over the value of an existing element. The class front_insert_iterator is used to insert items at the beginning of a collection. The function front_inserter creates an instance of a front_insert_iterator for a particular collection type. A front_insert_iterator can be used with deques and lists, but not with maps or sets.
Returns *this (the input iterator itself). front_insert_iterator& operator++ (); front_insert_iterator operator++ (int); Increments the insert iterator and returns *this. Non-member Function template front_insert_iterator front_inserter (Container& x) Returns a front_insert_iterator that will insert elements at the beginning of container x. This function allows you to create front insert iterators inline. Example // // ins_itr.
cout << endl << endl; cout << "Use an insert_iterator: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // A deque of four 1s. // deque d2(4, 1); // // Insert d2 at front of d. // copy(d2.begin(), d2.end(), front_inserter(d)); // // Output the new deque. // cout << endl << endl; cout << "Use a front_inserter: " << endl << " "; copy(d.begin(), d.end(), ostream_iterator(cout," ")); // // Insert d2 at back of d. // copy(d2.begin(), d2.
deque instead of: deque See Also Insert Iterators
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Function Objects Summary Objects with an operator() defined. Function objects are used in place of pointers to functions as arguments to templated algorithms.
Function objects that take one argument are called unary function objects. Unary function objects are required to provide the typedefs argument_type and result_type. Similarly, function objects that take two arguments are called binary function objects and, as such, are required to provide the typedefs first_argument_type, second_argument_type, and result_type. The classes unary_function and binary_function make the task of creating templated function objects easier.
Interface template struct unary_function{ typedef Arg argument_type; typedef Result result_type; }; template struct binary_function{ typedef Arg1 first_argument_type; typedef Arg2 second_argument_type; typedef Result result_type; }; // Arithmetic Operations template struct plus : binary_function { T operator() (const T&, const T&) const; }; template struct minus : binary_function { T operator() (const T&, c
struct not_equal_to : binary_function { bool operator() (const T&, const T&) const; }; template struct greater : binary_function { bool operator() (const T&, const T&) const; }; template struct less : binary_function { bool operator() (const T&, const T&) const; }; template struct greater_equal : binary_function { bool operator() (const T&, const T&) const; }; template struct less_equal : binary_function { bo
class factorial : public unary_function { public: Arg operator()(const Arg& arg) { Arg a = 1; for(Arg i = 2; i <= arg; i++) a *= i; return a; } }; int main() { //Initialize a deque with an array of ints int init[7] = {1,2,3,4,5,6,7}; deque d(init, init+7); //Create an empty vector to store the factorials vector v((size_t)7); //Transform the numbers in the deque to their factorials and // store in the vector transform(d.begin(), d.end(), v.
See Also binary_function, Iterators, unary_function
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software generate, generate_n Algorithm Summary Initialize a container with values produced by a value-generator class.
n). The function gen takes no arguments. (gen can be a function or a class with an operator () defined that takes no arguments.) generate_n assumes that there are at least n elements following first, unless first is an insert iterator. Complexity The generate and generate_n algorithms invoke gen and assign its return value exactly last first (or n) times. Example // // generate.cpp // #include #include #include
ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; // Generate 3 values for cout generate_n(ostream_iterator(cout," "),3,gen); cout << endl; return 0; } Output : 2 4 8 16 2 4 8 4 2 4 8 16 32 2 4 8 Warnings If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software greater Function Object Summary Binary function object that returns true if its first argument is greater than its second.
transform(vec1.begin(), vec1.end(), greater()); vec2.begin(), vecResult.begin(), After this call to transform, vecResult(n) will contain a "1" if vec1(n) was greater than vec2(n) or a "0" if vec1(n) was less than or equal to vec2(n). Warnings If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page.
. sort(vec1.begin(), vec1.end(),greater_equal()); After this call to sort, vec1 will be sorted in descending order. Warnings If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software includes Algorithm Summary Basic set operation for sorted sequences.
Complexity At most ((last1 - first1) + (last2 - first2)) * 2 -1 comparisons are performed. Example // // includes.cpp // #include #include #include int main() { //Initialize some sets int a1[10] = {1,2,3,4,5,6,7,8,9,10}; int a2[6] = {2,4,6,8,10,12}; int a3[4] = {3,5,7,8}; set > all(a1, a1+10), even(a2, a2+6), small(a3,a3+4); //Demonstrate includes cout << "The set: "; copy(all.begin(),all.end(), ostream_iterator(cout," ")); bool answer = includes(all.
Warnings If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software inner_product Generalized Numeric Operation Summary Computes the inner product A X B of two ranges A and B.
Description There are two versions of inner_product. The first computes an inner product using the default multiplication and addition operators, while the second allows you to specify binary operations to use in place of the default operations.
int inner_prod = inner_product(l.begin(), l.end(), v.begin(), 0); //Calculate a wacky inner product using the same values int wacky = inner_product(l.begin(), l.end(), v.begin(), 0, plus(), minus()); //Print the output cout << "For the two sets of numbers: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << " and "; copy(l.begin(),l.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software inplace_merge Algorithm Summary Merge two sorted sequences into one.
Description The inplace_merge algorithm merges two sorted consecutive ranges [first, middle) and [middle, last), and puts the result of the merge into the range [first, last). The merge is stable, that is, if the two ranges contain equivalent elements, the elements from the first range always precede the elements from the second. There are two versions of the inplace_merge algorithm.
inplace_merge(v5.begin(),mid,v5.end()); // Now use a comparator on v6 mid = v6.begin(); advance(mid,4); inplace_merge(v6.begin(),mid,v6.end(),less()); // Merge v1 and v2 to empty vector using insert iterator merge(v1.begin(),v1.end(),v2.begin(),v2.end(), back_inserter(v7)); // Copy all cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; copy(v3.begin(),v3.end(),out); cout << endl; copy(v4.begin(),v4.
Warnings If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Input Iterators Iterator Summary A read-only, forward moving iterator. Contents ● Description ● Key to Iterator Requirements ● Requirements for Input Iterators ● See Also Description For a complete discussion of iterators, see the Iterators section of this reference. Iterators are a generalization of pointers that allow a C++ program to uniformly interact with different data structures.
r value of type X& t value of type T Requirements for Input Iterators The following expressions must be valid for input iterators: X u(a) copy constructor, u == a Xu=a assignment, u == a a == b, a != b return value convertable to bool *a a == b implies *a == *b ++r returns X& r++ return value convertable to const X& *r++ returns type T a -> m returns (*a).m For input iterators, a == b does not imply that ++a == ++b. Algorithms using input iterators should be single pass algorithms.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Insert Iterators Insert Iterator Summary Iterator adaptor that allows an iterator to insert into a container rather than overwrite elements in the container.
● The class back_insert_iterator is used to insert items at the end of a collection. The function back_inserter can be used with an iterator inline, to create an instance of a back_insert_iterator for a particular collection type. ● The class front_insert_iterator is used to insert items at the start of a collection. The function front_inserter creates an instance of a front_insert_iterator for a particular collection type.
}; template insert_iterator inserter (Container&, Iterator); template back_insert_iterator back_inserter (Container&); template front_insert_iterator front_inserter (Container&); See Also back_insert_iterator, front_insert_iterator
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software insert_iterator, inserter Insert Iterator Summary An insert iterator used to insert items into a collection rather than overwrite the collection.
Description Insert iterators let you insert new elements into a collection rather than copy a new element's value over the value of an existing element. The class insert_iterator is used to insert items into a specified location of a collection. The function inserter creates an instance of an insert_iterator given a particular collection type and iterator. An insert_iterator can be used with vectors, deques, lists, maps and sets.
operator++ (int); Increments the insert iterator and returns *this. Non-member Function template insert_iterator inserter (Container& x, Iterator i); Returns an insert_iterator that will insert elements into container x at location i. This function allows you to create insert iterators inline. Example #include #include #include
vector See Also back_insert_iterator, front_insert_iterator, Insert Iterators
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software istream_iterator Iterators Summary Stream iterator that provides iterator capabilities for istreams. This iterator allows generic algorithms to be used directly on streams.
Description Stream iterators provide the standard iterator interface for input and output streams. The class istream_iterator reads elements from an input stream (using operator >>). A value of type T is retrieved and stored when the iterator is constructed and each time operator++ is called. The iterator will be equal to the end-of-stream iterator value if the end-of-file is reached. Use the constructor with no arguments to create an end-of-stream iterator.
Construct an istream_iterator on the given stream. istream_iterator (const istream_iterator& x); Copy constructor. Destructors ~istream_iterator (); Destructor. Operators const T& operator* () const; Return the current value stored by the iterator. const T* operator-> () const; Return a poinster to the current value stored by the iterator. istream_iterator& operator++ () istream_iterator operator++ (int) Retrieve the next element from the input stream.
{ vector d; int total = 0; // // Collect values from cin until end of file // Note use of default constructor to get ending iterator // cout << "Enter a sequence of integers (eof to quit): " ; copy(istream_iterator::difference_type>(cin), istream_iterator::difference_type>(), inserter(d,d.begin())); // // stream the whole vector and the sum to cout // copy(d.begin(),d.end()-1,ostream_iterator(cout," + ")); if (d.size()) cout << *(d.end()-1) << " = " << accumulate(d.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software iterator_category Iterator primitive Summary Determines the category an iterator belongs to.
Description The iterator_category family of function templates allows you to determine the category that any iterator belongs to. The first five functions take an iterator of a specific type and return the tag for that type. The last takes a T* and returns random_access_iterator_tag. Tag Types input_iterator_tag output_iterator_tag forward_iterator_tag bidirectional_iterator_tag random_access_iterator_tag The iterator_category function is particularly useful for improving the efficiency of algorithms.
See Also Other iterator primitives: value_type, distance_type, distance, advance
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Iterators Summary Pointer generalizations for traversal and modification of collections.
Iterators are a generalization of pointers that allow a C++ program to uniformly interact with different data structures. The illustration below displays the five iterator categories defined by the standard library, and shows their heirarchical relationship. Because standard library iterator categories are hierarchical, each category includes all the requirements of the categories above it.
Containers and sequences must also provide const iterators to the beginning and end of their collections. These may be accessed using the class members, begin() and end(). The semantics of iterators are a generalization of the semantics of C++ pointers. Every template function that takes iterators will work using C++ pointers for processing typed contiguous memory sequences.
For input iterators, a == b does not imply that ++a == ++b. Algorithms using input iterators should be single pass algorithms. That is they should not pass through the same iterator twice. The value of type T does not have to be an lvalue.
Forward iterators have the condition that a == b implies *a== *b. There are no restrictions on the number of passes an algorithm may make through the structure. Requirements for Bidirectional Iterators A bidirectional iterator must meet all the requirements for forward iterators.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software iter_swap Algorithm Summary Exchange values pointed at in two locations Contents ● Synopsis ● Description ● Example ● Warning ● See Also Synopsis #include template void iter_swap (ForwardIterator1, ForwardIterator2); Description The iter_swap algorithm exchanges the values pointed at by the two iterators a and b.
int d1[] = {6, 7, 8, 9, 10, 1, 2, 3, 4, 5}; // // Set up a vector. // vector v(d1+0, d1+10); // // Output original vector. // cout << "For the vector: "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); // // Swap the first five elements with the last five elements. // swap_ranges(v.begin(), v.begin()+5, v.begin()+5); // // Output result. // cout << endl << endl << "Swaping the first 5 elements with the last 5 gives: " << endl << " "; copy(v.begin(), v.
Warning If your compiler does not support default template parameters, then you will need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software less Function Object Summary Binary function object that returns true if its first argument is less than its second Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct less : public binary_function ; Description less is a binary function object. Its operator() returns true if x is less than y.
transform(vec1.begin(), vec1.end(), vecResult.begin(), less()); vec2.begin(), After this call to transform, vecResult(n) will contain a "1" if vec1(n) was less than vec2(n) or a "0" if vec1(n) was greater than or equal to vec2(n).
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software less_equal Function Object Summary Binary function object that returns true if its first argument is less than or equal to its second Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct less_equal : public binary_function; Description less_equal is a binary function object.
After this call to sort, vec1 will be sorted in ascending order.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software lexicographical_compare Algorithm Summary Compares two ranges lexicographically.
Description The lexicographical_compare functions compare each element in the range [first1, last1) to the corresponding element in the range [first2, last2) using iterators i and j. The first version of the algorithm uses operator< as the default comparison operator. It immediately returns true if it encounters any pair in which *i is less than *j, and immediately returns false if *j is less than *i.
Output: FALSE TRUE Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software limits Numeric Limits library Refer to the numeric_limits section of this reference guide.
Click on the banner to return to the Class Reference home page.
and u is a const value of T): Default constructor Copy constructors Destructor Address of Assignment T() T(t) and T(u) t.
const_reverse_iterator rend () const; // Capacity bool empty () const; size_type size () const; size_type max_size () const; void resize (size_type); void resize (size_type, T); // Element Access reference front (); const_reference front () const; reference back (); const_reference back () const; // Modifiers void push_front (const T&); void pop_front (); void push_back (const T&); void pop_back (); iterator insert (iterator); iterator insert (iterator, const T&); void insert (iterator, size_type, const T&)
// Specialized Algorithms template void swap (list&, list&); Constructors and Destructors explicit list (const Allocator& alloc = Allocator()); Creates a list of zero elements. The list will use the allocator alloc for all storage management. explicit list (size_type n, const Allocator& alloc = Allocator()); Creates a list of length n, containing n copies of the default value for type T. Requires that T have a default constructor.
Returns a bidirectional iterator that points to the past-the-end value. const_iterator end () const; Returns a constant bidirectional iterator that points to the past-the-end value. reverse_iterator rbegin (); Returns a bidirectional iterator that points to the past-the-end value. const_reverse_iterator rbegin () const; Returns a constant bidirectional iterator that points to the past-the-end value. reverse_iterator rend (); Returns a bidirectional iterator that points to the first element.
Removes the element pointed to by position. Returns an iterator pointing to the element following the deleted element, or end() if the deleted item was the last one in this list. iterator erase (iterator first, iterator last); Removes the elements in the range (first, last). Returns an iterator pointing to the element following the element following the last deleted element, or end() if there were no elements after the deleted range. reference front (); Returns a reference to the first element.
void pop_front (); Removes the first element. void push_back (const T& x); Appends a copy of x to the end of the list. void push_front (const T& x); Appends a copy of x to the front of the list. void remove (const T& value); template void remove_if (Predicate pred); Removes all elements in the list referred by the list iterator i for which *i == value or pred(*i) == true, whichever is applicable.
splice (iterator position, list& x); Inserts x before position leaving x empty. void splice (iterator position, list& x, iterator i); Moves the elements pointed to by iterator i in x to self, inserting it before position. The element is removed from x. void splice (iterator position, list& iterator first, iterator last); x, Moves the elements in the range [first, last) in x to self, inserting before position.
#include #include // Print out a list of strings ostream& operator<<(ostream& out, const list& l) { copy(l.begin(), l.end(), ostream_iterator(cout," ")); return out; } int main(void) { // create a list of critters list critters; int i; // insert several critters critters.insert(critters.begin(),"antelope"); critters.insert(critters.begin(),"bear"); critters.insert(critters.
Warnings Member function templates are used in all containers provided by the Standard Template Library. An example of this feature is the constructor for list that takes two templated iterators: template list (InputIterator, InputIterator, const Allocator& = Allocator()); list also has an insert function of this type. These functions, when not restricted by compiler limitations, allow you to use any type of input iterator as arguments.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software logical_and Function Object Summary Binary function object that returns true if both of its arguments are true. Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct logical_and : public binary_function; Description logical_and is a binary function object. Its operator() returns true if both x and y are true.
transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), logical_and()); After this call to transform, vecResult(n) will contain a "1" (true) if both vec1(n) and vec2(n) are true or a "0" (false) if either vec1(n) or vec2(n) is false.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software logical_not Function Object Summary Unary function object that returns true if its argument is false. Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct logical_not : unary_function ; Description logical_not is a unary function object. Its operator() returns true if its argument is false.
logical_not(),1); This call to replace_if replaces all zeros in the vec1 with "1". Interface template struct logical_not : unary_function { typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; bool operator() (const T&) const; }; Warning If your compiler does not support default template parameters, you will need to always supply the Allocator template arguement.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software logical_or Function Object Summary Binary function object that returns true if either of its arguments are true. Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct logical_or : binary_function ; Description logical_or is a binary function object. Its operator() returns true if either x or y are true.
vec2.begin(), vecResult.begin(), logical_or()); After this call to transform, vecResult(n) will contain a "1" (true) if either vec1(n) or vec2(n) is true or a "0" (false) if both vec1(n) and vec2(n) are false.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software lower_bound Algorithm Summary Determine the first valid position for an element in a sorted container.
ordering. There are two versions of the algorithm. The first uses the less than operator (operator<) to perform the comparison, and assumes that the sequence has been sorted using that operator. The second version lets you include a function object of type Compare, and assumes that Compare is the function used to sort the sequence. The function object must be a binary predicate.
upper_bound(v1.begin(),v1.end(),2,less()); // it4 = v1.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software make_heap Algorithm Summary Creates a heap.
Description A heap is a particular organization of elements in a range between two random access iterators [a, b). Its two key properties are: 1. *a is the largest element in the range. 2. *a may be removed by the pop_heap algorithm, or a new element can be added by the push_heap algorithm, in O(logN) time. These properties make heaps useful as priority queues. The heap algorithms use less than (operator<) as the default comparison.
// does not require any particular ordering // of these values. // Copy both vectors to cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now let's pop pop_heap(v1.begin(),v1.end()); pop_heap(v2.begin(),v2.end(),less()); // v1 = (3,x,y,4) and v2 = (3,x,y,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // And push push_heap(v1.begin(),v1.
4 3 2 1 1 2 3 4 1 2 3 4 Warning If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software map Container Summary An associative container providing access to non-key values using unique keys. A map supports bidirectional iterators.
class Allocator = allocator> class map; Description map provides fast access to stored values of type T which are indexed by unique keys of type Key. The default operation for key comparison is the < operator. map provides bidirectional iterators that point to an instance of pair where x is the key and y is the stored value associated with that key. The definition of map provides a typedef to this pair called value_type.
// // // // // class value_compare : public binary_function { friend class map; public : bool operator() (const value_type&, const value_type&) const; }; Construct/Copy/Destroy explicit map (const Compare& = Compare(), const Allocator& = Allocator ()); template map (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator ()); map (const map&); ~map(); map
// Observers key_compare key_comp() const; value_compare value_comp() const; // Map operations iterator find (const key_value&); const_iterator find (const key_value&) const; size_type count (const key_type&) const; iterator lower_bound (const key_type&); const_iterator lower_bound (const key_type&) const; iterator upper_bound (const key_type&); const_iterator upper_bound (const key_type&) const; pair equal_range (const key_type&); pair equal_range (const
Copy constructor. Creates a new map by copying all pairs of key and value from x. ~map (); The destructor. Releases any allocated memory for this map. Allocator allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management. Iterators iterator begin() ; Returns an iterator pointing to the first element stored in the map. "First" is defined by the map's comparison operator, Compare.
Assignment. Replaces the contents of *this with a copy of the map x. mapped_type& operator[] (const key_type& x); If an element with the key x exists in the map, then a reference to its associated value will be returned. Otherwise the pair x,T() will be inserted into the map and a reference to the default object T() will be returned. Allocator allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management.
pointing to the element following the last deleted element, or end() if there were no elements after the deleted range. size_type erase (const key_type& x); Deletes the element with the key value x from the map, if one exists. Returns 1 if x existed in the map, 0 otherwise. iterator find (const key_type& x); Searches the map for a pair with the key value x and returns an iterator to that pair if it is found. If such a pair is not found the value end() is returned.
size_type max_size() const; Returns the maximum possible size of the map. This size is only constrained by the number of unique keys which can be represented by the type Key. size_type size() const; Returns the number of elements in the map. void swap (map& x); Swaps the contents of the map x with the current map, *this. iterator upper_bound (const key_type& x); Returns a reference to the first entry with a key less than or equal to x.
Example // // map.cpp // #include #include
// print out the months // Second Febuary is not present cout << months << endl; // Find the Number of days in June months_type::iterator p = months.find(string("June")); // print out the number of days in June if (p != months.
first_map.end()); But not this way: map > long_map(first_map.begin(), first_map.end()); Since the long_map and first_map are not the same type. Also, many compilers do not support default template arguments. If your compiler is one of these, you need to always supply the Compare template argument and the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software max Algorithm Summary Find and return the maximum of a pair of values Contents ● Synopsis ● Description ● Example ● See Also Synopsis #include template const T& max(const T&, const T&); template const T& max(const T&, const T&, Compare); Description The max algorithm determines and returns the maximum of a pair of values.
Example // // max.cpp // #include #include #include int main(void) { double d1 = 10.0, d2 = 20.0; // Find minimum double val1 = min(d1, d2); // val1 = 10.0 // the greater comparator returns the greater of the // two values. double val2 = min(d1, d2, greater()); // val2 = 20.0; // Find maximum double val3 = max(d1, d2); // val3 = 20.0; // the less comparator returns the smaller of the two values.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software max_element Algorithm Summary Finds maximum value in a range.
Description The max_element algorithm returns an iterator that denotes the maximum element in a sequence. If the sequence contains more than one copy of the element, the iterator points to its first occurrence. The optional argument comp defines a comparison function that can be used in place of the default operator<. This function can be used with all the datatypes provided by the standard library.
// find the smallest element iterator it3 = min_element(v1.begin(), v1.end()); // it3 = v1.begin() // find the smallest value in the range from // the beginning of the vector plus 1 to the end iterator it4 = min_element(v1.begin()+1, v1.end(), less()); // it4 = v1.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software merge Algorithm Summary Merge two sorted sequences into a third sequence.
OutputIterator result, Compare comp); Description The merge algorithm merges two sorted seqeunces, specified by [first1, last1) and [first2, last2), into the sequence specified by [result, result + (last1 - first1) + (last2 - first2)). The first version of the merge algorithm uses the less than operator (<) to compare elements in the two sequences. The second version uses the comparision function provided by the function call.
merge(v1.begin(),v1.end(),v2.begin(),v2.end(),v3.begin()); // Now use comparator merge(v1.begin(),v1.end(),v2.begin(),v2.end(),v4.begin(), less()); // In place merge v5 vector::iterator mid = v5.begin(); advance(mid,4); inplace_merge(v5.begin(),mid,v5.end()); // Now use a comparator on v6 mid = v6.begin(); advance(mid,4); inplace_merge(v6.begin(),mid,v6.end(),less()); // Merge v1 and v2 to empty vector using insert iterator merge(v1.begin(),v1.end(),v2.begin(),v2.
11 12 13 14 15 16 17 18 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 Warning If your compiler does not support default template parameters then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software min Algorithm Summary Find and return the minimum of a pair of values Contents ● Synopsis ● Description ● Example ● See Also Synopsis #include template const T& min(const T&, const T&); template const T& min(const T& a, const T&, Compare); Description The min algorithm determines and returns the minimum of a pair of values.
Example // // max.cpp // #include #include int main(void) { double d1 = 10.0, d2 = 20.0; // Find minimum double val1 = min(d1, d2); // val1 = 10.0 // the greater comparator returns the greater of the // two values. double val2 = min(d1, d2, greater()); // val2 = 20.0; // Find maximum double val3 = max(d1, d2); // val3 = 20.0; // the less comparator returns the smaller of the // two values.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software min_element Algorithm Summary Finds the minimum value in a range.
Description The min_element algorithm returns an iterator that denotes the minimum element in a sequence. If the sequence contains more than one copy of the minimum element, the iterator points to the first occurrence of the element. In the second version of the function, the optional argument comp defines a comparison function that can be used in place of the default operator<. This function can be used with all the datatypes provided by the standard library.
// find the smallest element iterator it3 = min_element(v1.begin(), v1.end()); // it3 = v1.begin() // find the smallest value in the range from // the beginning of the vector plus 1 to the end iterator it4 = min_element(v1.begin()+1, v1.end(), less()); // it4 = v1.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software minus Function Object Summary Returns the result of subtracting its second argument from its first. Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct minus : public binary_function; Description minus is a binary function object. Its operator() returns the result of x minus y.
transform(vec1.begin(), vec1.end(), vecResult.begin(), minus()); vec2.begin(), After this call to transform, vecResult(n) will contain vec1(n) minus vec2(n).
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software mismatch Algorithm Summary Compares elements from two sequences and returns the first two elements that don't match each other.
Description The mismatch algorithm compares members of two sequences and returns two iterators (i and j) that point to the first location in each sequence where the sequences differ from each other. Notice that the algorithm denotes both a starting position and an ending position for the first sequence, but denotes only a starting position for the second sequence. mismatch assumes that the second sequence has at least as many members as the first sequence.
// p1 will contain two iterators that point to the // first pair of elements that are different between // the two vectors pair p1 = mismatch(vi1.begin(), vi1.end(), vi2.begin()); // find the first two elements such that an element in the // first vector is greater than the element in the second // vector. pair p2 = mismatch(vi1.begin(), vi1.end(), vi2.begin(), less_equal()); // Output results cout << *p1.first << ", " << *p1.second << endl; cout << *p2.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software modulus Function Object Summary Returns the remainder obtained by dividing the first argument by the second argument. Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct modulus : public binary_function ; Description modulus is a binary function object.
transform(vec1.begin(), vec1.end(), vec2.begin(), vecResult.begin(), modulus()); After this call to transform, vecResult(n) will contain the remainder of vec1(n) divided by vec2(n).
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software multimap Container Summary An associative container providing access to non-key values using keys. multimap keys are not required to be unique. A multimap supports bidirectional iterators.
Description multimap provides fast access to stored values of type T which are indexed by keys of type Key. The default operation for key comparison is the < operator. Unlike map, multimap allows insertion of duplicate keys. multimap provides bidirectional iterators which point to an instance of pair where x is the key and y is the stored value associated with that key. The definition of multimap provides a typedef to this pair called value_type.
// // // // // // }; Construct/Copy/Destroy explicit multimap (const Compare& = Compare(), const Allocator& = Allocator()); template multimap (InputIterator, InputIterator, const Compare& = Compare(), const Allocator& = Allocator()); multimap (const multimap&); ~multimap (); multimap& operator= (const multimap&); Iterators iterator begin (); const_iterator begin () const; iterator end (); const_it
}; // Non-member Operators template bool operator== (const multimap&, const multimap&); template bool operator< (const multimap&, const multimap&); // Specialized Algorithms template void swap (multimap&, multimap<
Iterators iterator begin() ; Returns a bidirectional iterator pointing to the first element stored in the multimap. "First" is defined by the multimap's comparison operator, Compare. const_iterator begin() const; Returns a const_iterator pointing to the first element stored in the multimap. "First" is defined by the multimap's comparison operator, Compare. iterator end() ; Returns a bidirectional iterator pointing to the last element stored in the multimap, i.e. the off-the-end value.
equal_range (const key_type& x) const; Returns the pair (lower_bound(x), upper_bound(x)). iterator erase (iterator first, iterator last); Providing the iterators first and last point to the same multimap and last is reachable from first, all elements in the range (first, last) will be deleted from the multimap. Returns an iterator pointing to the element following the last deleted element, or end(), if there were no elements after the deleted range.
Compare, of the current multimap. iterator lower_bound (const key_type& x); Returns an iterator to the first multimap element whose key is greater than or equal to x. If no such element exists then end() is returned. const_iterator lower_bound (const key_type& x) const; Same as lower_bound above but returns a const_iterator. size_type max_size() const; Returns the maximum possible size of the multimap. size_type size() const; Returns the number of elements in the multimap.
Returns true if x is lexicographically less than y. Otherwise, it returns false. template void swap (multimap& a, multimap& b); Efficiently swaps the contents of a and b. Example // // multimap.cpp // #include #include
months.insert(value_type(31, string("October"))); months.insert(value_type(30, string("November"))); months.insert(value_type(31, string("December"))); // print out the months cout << "All months of the year" << endl << months << endl; // Find the Months with 30 days pair p = months.equal_range(30); // print out the 30 day months cout << endl << "Months with 30 days" << endl; copy(p.first,p.
type of container as the one you are constructing (or calling a member function on), or you can use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates you can construct a multimap in the following two ways: multimap, allocator>::value_type intarray[10]; multimap, allocator> first_map(intarry, intarray + 10); multimap, allocator> second_multimap(first_multimap.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software multiset Container Class Summary An associative container providing fast access to stored key values. Storage of duplicate keys is allowed. A multiset supports bidirectional iterators.
Description multiset provides fast access to stored key values. The default operation for key comparison is the < operator. Insertion of dupliate keys is allowed with a multiset. multiset provides bidirectional iterators which point to a stored key. Any type used for the template parameter Key must provide the following (where T is the type, t is a value of T and u is a const value of T): Copy constructors T(t) and T(u) Destructor t.
multiset& operator= (const multiset&); // Iterators iterator begin (); const_iterator begin () const; iterator end (); const_iterator end () const; reverse_iterator rbegin (); const_reverse_iterator rbegin () const; reverse_iterator rend (); const_reverse_iterator rend () const; // Capacity bool empty () const; size_type size () const; size_type max_size () const; // Modifiers iterator insert (const value_type&); iterator insert (iterator, const value_type&)
void swap ( multiset&, multiset&); Constructor and Destructor explicit multiset (const Compare& comp = Compare(), const Allocator& alloc = Allocator()); Default constructor. Constructs an empty multiset which will use the optional relation comp to order keys, if it is supplied, and the allocator alloc for all storage management.
Returns a const_iterator pointing to the last element stored in the multiset, i.e., the off-the-end value. reverse_iterator rbegin(); Returns a reverse_iterator pointing to the first element stored in the multiset. "First" is defined by the multiset's comparison operator, Compare. const_reverse_iterator rbegin(); Returns a const_reverse_iterator pointing to the first element stored in the multiset. reverse_iterator rend(); Returns a reverse_iterator pointing to the last element stored in the multiset, i.e.
erase (iterator first, iterator last); Providing the iterators first and last point to the same multiset and last is reachable from first, all elements in the range (first, last) will be deleted from the multiset. Returns an iterator pointing to the element following the last deleted element, or end() if there were no elements after the deleted range. iterator find (const key_type& x) const; Searches the multiset for a key value x and returns an iterator to that key if it is found.
upper_bound (const key_type& x) const; Returns an iterator to the first element whose key is smaller than or equal to x. If no such element exists then end() is returned. value_compare value_comp () const; Returns a function object capable of comparing key values using the comparison operation, Compare, of the current multiset.
for (int j = 0; j < 2; j++) { for(i = 0; i < 10; ++i) { // insert values with a hint si.insert(si.begin(), i); } } // print out the multiset cout << si << endl; // Make another int multiset and an empty multiset set_type si2, siResult; for (i = 0; i < 10; i++) si2.insert(i+5); cout << si2 << endl; // Try a couple of set algorithms set_union(si.begin(),si.end(),si2.begin(),si2.end(), inserter(siResult,siResult.begin())); cout << "Union:" << endl << siResult << endl; siResult.erase(siResult.begin(),siResult.
the same type of container as the one you are constructing (or calling a member function on). You can also use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates, you can construct a multiset in the following two ways: int intarray[10]; multiset, allocator> first_multiset(intarray, intarray +10); multiset , allocator> second_multiset(first_multiset.begin(), first_multiset.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software negate Function Object Summary Unary function object that returns the negation of its argument. Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct negate : public unary_function; Description negate is a unary function object. Its operator() returns the negation of its argument, i.e.
typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; T operator() (const T&) const; }; Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Negators Function Object Summary Function adaptors and function objects used to reverse the sense of predicate function objects.
unary_negate and binary_negate are function object classes that provide return types for the negators, not1 and not2.
Example // // negator.cpp // #include #include #include
See Also Algorithms, binary_function, Function Objects, unary_function
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software next_permutation Algorithm Summary Generate successive permutations of a sequence based on an ordering function.
six permutations, which, in order from first to last are: 1 2 3 , 1 3 2, 2 1 3, 2 3 1, 3 1 2, and 3 2 1. The next_permutation algorithm takes a sequence defined by the range [first, last) and transforms it into its next permutation, if possible. If such a permutation does exist, the algorithm completes the transformation and returns true.
prev_m2.end(),less()); next_permutation(next_m2.begin(), next_m2.end(),less()); //Output results cout << "Example 1: " << endl << " "; cout << "Original values: "; copy(m1.begin(),m1.end(), ostream_iterator(cout," ")); cout << endl << " "; cout << "Previous permutation: "; copy(prev_m1.begin(),prev_m1.end(), ostream_iterator(cout," ")); cout << endl<< " "; cout << "Next Permutation: "; copy(next_m1.begin(),next_m1.
Warning If your compiler does not support default template parameters, the you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software not1 Function Adaptor Summary Function adaptor used to reverse the sense of a unary predicate function object.
See Also Negators, not2, unary_function, unary_negate, pointer_to_unary_function
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software not2 Function Adaptor Summary Function adaptor used to reverse the sense of a binary predicate function object.
See Also binary_function, binary_negate, Negators, not1, pointer_to_binary_function, unary_negate
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software not_equal_to Function Object Summary Binary function object that returns true if its first argument is not equal to its second. Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct not_equal_to : public binary_function ; Description not_equal_to is a binary function object.
vecResult.begin(), not_equal_to()); After this call to transform, vecResult(n) will contain a "1" if vec1(n) was not equal to vec2(n) or a "1" if vec1(n) was equal to vec2(n).
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software nth_element Algorithm Summary 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.
Description The nth_element algorithm rearranges a collection according to either the default comparison operator (>) or the provided comparison operator.
if(dist == 2 && *end < *start) swap(start, end); } int main() { //Initialize a vector using an array of ints int arr[10] = {37, 12, 2, -5, 14, 1, 0, -1, 14, 32}; vector v(arr, arr+10); //Print the initial vector cout << "The unsorted values are: " << endl << " "; vector::iterator i; for(i = v.begin(); i != v.end(); i++) cout << *i << ", "; cout << endl << endl; //Use the new sort algorithm quik_sort(v.begin(), v.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software numeric_limits Numeric Limits Library Summary A class for representing information about scalar types.
numeric_limits numeric_limits numeric_limits Synopsis #include template class numeric_limits ; Description numeric_limits is a class for representing information about scalar types. Specializations are provided for each fundamental type, both floating point and integer, including bool.
static static static static static static static static static static static static static static const int max_exponent10 ; const int min_exponent ; const int max_exponent ; const bool has_infinity ; const bool has_quiet_NaN ; const bool has_signaling_NaN ; const bool is_iec559 ; const bool has_denorm ; const bool tinyness_before ; const float_round_style round_style ; T denorm_min (); T infinity (); T quiet_NaN (); T signaling_NaN (); }; enum float_round_style { round_indeterminate round_toward_zero rou
Returns the machine epsilon (the difference between 1 and the least value greater than 1 that is representable). This function is meaningful for floating point types only. static const bool has_denorm ; This field is true if the type allows denormalized values (variable number of exponent bits). It is meaningful for floating point types only. static const bool has_infinity ; This field is true if the type has a representation for positive infinity. It is meaningful for floating point types only.
This member is true if and only if the type adheres to the IEC 559 standard. It is meaningful for floating point types only. Must be true for any type claiming conformance to IEC 559. static const bool is_integer ; This member is true if the type is integer. This member is meaningful for all specializations. static const bool is_modulo ; This field is true if the type is modulo. Generally, this is false for floating types, true for unsigned integers, and true for signed integers on most machines.
provided by denorm_min(). This function is meaningful for all specializations that declare is_bounded to be true. static const int min_exponent ; Minimum negative integer such that the radix raised to that power is in range. This field is meaningful for floating point types only. static const int min_exponent10 ; Minimum negative integer such that 10 raised to that power is in range. This field is meaningful for floating point types only.
static const bool traps ; This field is true if trapping is implemented for this type. The traps field is meaningful for all specializations. Example // // limits.cpp // #include int main() { numeric_limits float_info; if (float_info.is_specialized && float_info.has_infinity) { // get value of infinity float finfinity=float_info.
Click on the banner to return to the Class Reference home page.
operator>= returns !(x
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software ostream_iterator Iterator Summary Stream iterators provide iterator capabilities for ostreams and istreams. They allow generic algorithms to be used directly on streams.
Description Stream iterators provide the standard iterator interface for input and output streams. The class ostream_iterator writes elements to an output stream. If you use the constructor that has a second, char * argument, then that string will be written after every element . (The string must be null-terminated.) Since an ostream iterator is an output iterator, it is not possible to get an element out of the iterator. You can only assign to it.
Operators const T& operator= (const T& value); Shift the value T onto the output stream. const T& ostream_iterator& operator* (); ostream_iterator& operator++(); ostream_iterator operator++ (int); These operators all do nothing. They simply allow the iterator to be used in common constructs. Example #include #include #include #include int main () { // // Initialize a vector using an array.
instead of : deque See Also istream_iterator, Iterators
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Output Iterators Iterator Summary A write-only, forward moving iterator. Contents ● Description ● Key to Iterator Requirements ● Requirements for Output Iterators ● See Also Description For a complete discussion of iterators, see the Iterators section of this reference. Iterators are a generalization of pointers that allow a C++ program to uniformly interact with different data structures.
r value of type X& t value of type T Requirements for Output Iterators The following expressions must be valid for output iterators: X(a) copy constructor, a == X(a). X u(a) copy constructor, u == a X u = a assignment, u == a *a = t result is not used ++r returns X& r++ return value convertable to const X& *r++ = t result is not used The only valid use for the operator * is on the left hand side of the assignment statement. Algorithms using output iterators should be single pass algorithms.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software pair Utility Class Summary A template for heterogenous pairs of values. Contents ● Synopsis ● Description ● Interface ● Constructors and Destructors ● Non-member Operators ● Non-member Functions Synopsis #include template struct pair ; Description The pair class provides a template for encapsulating pairs of values that may be of different types.
T1 first; T2 second; pair(); pair (const T1&, const T2&); ~pair(); }; template bool operator== (const pair&, const pair T1, T2>&); template bool operator< (const pair&, const pair T1, T2>&); template pair make_pair (const T1&, const T2&); Constructors and Destructors pair (); Default contructor. Initializes first and second using their default constructors.
Non-member Functions template pair make_pair(x,y); make_pair(x,y) creates a pair by deducing and returning the types of x and y.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software partial_sort Algorithm Summary Templated algorithm for sorting collections of entities.
defined order. The first version of the algorithm uses less than (operator<) as the comparison operator for the sort. The second version uses the comparision function comp. Complexity partial_sort does approximately (last - first) * log(middle-first) comparisons. Example // // partsort.cpp // #include #include #include int main() { int d1[20] = {17, 3, 5, -4, 1, 12, -10, -1, 14, 7, -6, 8, 15, -11, 2, -2, 18, 4, -3, 0}; // // Set up a vector.
v2.end()); // // Output result. // cout << endl << "A partial_sort_copy of the last ten elements gives: " << endl << " "; copy(v2.begin(), v2.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software partial_sort_copy Algorithm Summary Templated algorithm for sorting collections of entities.
Complexity partial_sort_copy does approximately (last-first) * log(min(last-first, result_last-result_first)) comparisons. Example // // partsort.cpp // #include #include #include int main() { int d1[20] = {17, 3, 5, -4, 1, 12, -10, -1, 14, 7, -6, 8, 15, -11, 2, -2, 18, 4, -3, 0}; // // Set up a vector. // vector v1(d1+0, d1+20); // // Output original vector. // cout << "For the vector: "; copy(v1.begin(), v1.
A partial_sort_copy of the last ten elements gives: 0 1 2 3 4 5 7 8 15 18 Warning If your compiler does not support default template parameters, then you need to always provide the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software partial_sum Generalized Numeric Operation Summary Calculates successive partial sums of a range of values.
binary_op(binary_op(..., binary_op (*first, *(first + 1)),...),*(first + (i result))) For instance, applying partial_sum to (1,2,3,4,) will yield (1,3,6,10). The partial_sum algorithm returns result + (last - first). If result is equal to first, the elements of the new sequence successively replace the elements in the original sequence, effectively turning partial_sum into an inplace transformation. Complexity Exactly (last - first) - 1 applications of the default + operator or binary_op are performed.
Warning If your compiler does not support default template parameters, then you need to always provide the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software partition Algorithm Summary Places all of the entities that satisfy the given predicate before all of the entities that do not.
in the range[first, i), pred(*j) == true, and, for any iterator k in the range [i, last), pred(*j) == false. Note that partition does not necessarily maintain the relative order of the elements that match and elements that do not match the predicate. Use the algorithm stable_partition if relative order is important. Complexity The partition algorithm does at most (last - first)/2 swaps, and applies the predicate exactly last - first times. Example // // prtition.
// A partition of the deque according to even/oddness. // partition(d2.begin(), d2.end(), is_even()); // // Output result of partition. // cout << "Partitioned values: " << "\t\t"; copy(d2.begin(), d2.end(), ostream_iterator(cout," ")); cout << endl; // // A stable partition of the deque according to even/oddness. // stable_partition(d1.begin(), d1.end(), is_even()); // // Output result of partition. // cout << "Stable partitioned values: " << "\t"; copy(d1.begin(), d1.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software permutation Algorithm Summary Generate successive permutations of a sequence based on an ordering function. See the entries for next_permutation and prev_permutation.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software plus Function Object Summary A binary function object that returns the result of adding its first and second arguments. Contents ● Synopsis ● Description ● Interface ● Warning ● See Also Synopsis #include template struct plus : public binary_function ; Description plus is a binary function object. Its operator() returns the result of adding x and y.
vecResult.begin(), plus()); After this call to transform, vecResult(n) will contain vec1(n) plus vec2(n).
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software pointer_to_binary_function Function Object Summary A function object which adapts a pointer to a binary function to work where a binary_function is called for.
typedef typename binary_function::second_argument_type second_argument_type; typedef typename binary_function::first_argument_type first_argument_type; typedef typename binary_function::result_type result_type; explicit pointer_to_binary_function (Result (*f)(Arg1, Arg2)); Result operator() (const Arg1&, const Arg2&) const; }; template pointer_to_binary_function ptr_fun (Result (*x)(Arg1, Ar
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software pointer_to_unary_function Function Object Summary A function object class that adapts a pointer to a function to work where a unary_function is called for.
typedef typename unary_function::result_type result_type; explicit pointer_to_unary_function (Result (*f)(Arg)); Result operator() (const Arg&) const; }; template pointer_to_unary_function ptr_fun (Result (*f)(Arg)); See Also Function Objects, pointer_to_binary_function, ptr_fun, unary_function
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software pop_heap Algorithms Summary Moves the largest element off the heap.
1. *a is the largest element in the range. 2. *a may be removed by the pop_heap algorithm or a new element added by the push_heap algorithm, in O(logN) time. These properties make heaps useful as priority queues. The pop_heap algorithm uses the less than (<) operator as the default comparison. An alternate comparison operator can be specified. The pop_heap algorithm can be used as part of an operation to remove the largest element from a heap. It assumes that the range [first, last) is a valid heap (i.e.
// Copy both vectors to cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now let's pop pop_heap(v1.begin(),v1.end()); pop_heap(v2.begin(),v2.end(),less()); // v1 = (3,x,y,4) and v2 = (3,x,y,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // And push push_heap(v1.begin(),v1.end()); push_heap(v2.begin(),v2.
1 2 3 4 1 2 3 4 Warning If your compiler does not support default template parameters, you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Predicates Summary A function or a function object that returns a boolean (true/false) value or an integer value.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software prev_permutation Algorithm Summary Generate successive permutations of a sequence based on an ordering function.
six permutations, which, in order from first to last, are: 1 2 3 , 1 3 2, 2 1 3, 2 3 1, 3 1 2, and 3 2 1. The prev_permutation algorithm takes a sequence defined by the range [first, last) and transforms it into its previous permutation, if possible. If such a permutation does exist, the algorithm completes the transformation and returns true.
next_m1.end(),less()); prev_permutation(prev_m2.begin(), prev_m2.end(),less()); next_permutation(next_m2.begin(), next_m2.end(),less()); //Output results cout << "Example 1: " << endl << " "; cout << "Original values: "; copy(m1.begin(),m1.end(), ostream_iterator(cout," ")); cout << endl << " "; cout << "Previous permutation: "; copy(prev_m1.begin(),prev_m1.end(), ostream_iterator(cout," ")); cout << endl<< " "; cout << "Next Permutation: "; copy(next_m1.begin(),next_m1.
Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software priority_queue Container Adaptor Summary A container adapter which behaves like a priority queue. Items are popped from the queue are in order with respect to a "priority.
Description priority_queue is a container adaptor which allows a container to act as a priority queue. This means that the item with the highest priority, as determined by either the default comparison operator (operator <) or the comparison Compare, is brought to the front of the queue whenever anything is pushed onto or popped off the queue. priority_queue adapts any container that provides front(), push_back() and pop_back(). In particular, deque, list, and vector can be used.
template priority_queue (InputIterator first, InputIterator last, const Compare& x = Compare(), const Allocator& alloc = Allocator()); Constructs a new priority queue and places into it every entity in the range [first, last). The priority_queue will use x for determining the priority, and the allocator alloc for all storage management. Allocator allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management.
#include #include int main(void) { // Make a priority queue of int using a vector container priority_queue, less, allocator> pq; // Push a couple of values pq.push(1); pq.push(2); // Pop a couple of values and examine the ends cout << pq.top() << endl; pq.pop(); cout << pq.top() << endl; pq.
return 0; } Output : 2 1 a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa aaaaaaaaa aaaaaaaa aaaaaaa aaaaaa aaaaa aaaa aaa aa a a a a a a a a a a a a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa
Warning If your compiler does not support default template parameters, you must always provide a Container template parameter, a Compare template parameter, and an Allocator template parameter when declaring an instance of priority_queue.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software ptr_fun Function Adaptor Summary A function that is overloaded to adapt a pointer to a function to work where a function is called for.
the function. The ptr_fun function is overloaded to create instances of pointer_to_unary_function or pointer_to_binary_function when provided with the appropriate pointer to a function. Example // // pnt2fnct.cpp // #include #include #include #include #include
1 2 6 24 120 720 5040 Warning If your compiler does not support default template parameters, you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software push_heap Algorithms Summary Places a new element into a heap.
Description A heap is a particular organization of elements in a range between two random access iterators [a, b). Its two key properties are: 1. *a is the largest element in the range. 2. *a may be removed by the pop_heap algorithm, or a new element added by the push_heap algorithm, in O(logN) time. These properties make heaps useful as priority queues. The push_heap algorithms uses the less than (<) operator as the default comparison.
// v1 = (4,x,y,z) and v2 = (4,x,y,z) // Note that x, y and z represent the remaining // values in the container (other than 4). // The definition of the heap and heap operations // does not require any particular ordering // of these values. // Copy both vectors to cout ostream_iterator out(cout," "); copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now let's pop pop_heap(v1.begin(),v1.end()); pop_heap(v2.begin(),v2.
Output : 4 2 3 1 4 3 2 1 3 2 1 4 3 1 2 4 4 3 1 2 4 3 2 1 1 2 3 4 1 2 3 4 Warning If your compiler does not support default template parameters, you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software queue Container Adaptor Summary A container adaptor that behaves like a queue (first in, first out).
Description The queue container adaptor lets a container function as a queue. In a queue, items are pushed into the back of the container and removed from the front. The first items pushed into the queue are the first items to be popped off of the queue (first in, first out, or "FIFO"). queue can adapt any container that supports the front(), back(), push_back() and pop_front() operations. In particular, deque, list, and vector can be used.
management. Allocator allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management. Member Functions value_type& back (); Returns a reference to the item at the back of the queue (the last item pushed into the queue). const value_type& back() const; Returns a constant reference to the item at the back of the queue as a const_value_type. bool empty () const; Returns true if the queue is empty, otherwise false.
Non-member Operators template bool operator== (const queue& x, const queue& y); Equality operator. Returns true if x is the same as y.
{ cout << qs.front() << endl; qs.pop(); } return 0; } Output : 1 2 a a a a a a a a a a a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa Warnings If your compiler does not support default template parameters, you must always provide a Container template parameter and an Allocator template parameter.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Random Access Iterators Iterator Summary An iterator that reads and writes, and provides random access to a container. Contents ● Description ● Key to Iterator Requirements ● Requirements for Random Access Iterators ● See Also Description For a complete discussion of iterators, see the Iterators section of this reference.
r value of type X& t value of type T Requirements for Random Access Iterators The following expressions must be valid for random access iterators: Xu u might have a singular value X() X() might be singular X(a) copy constructor, a == X(a). X u(a) copy constructor, u == a Xu=a assignment, u == a a == b, a != b return value convertable to bool *a return value convertable to T& a->m equivalent to (*a).
There are no restrictions on the number of passes an algorithm may make through the structure. All relational operators return a value convertable to bool.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software random_shuffle Algorithm Summary Randomly shuffles elements of a collection.
Description The random_shuffle algorithm shuffles the elements in the range [first, last) with uniform distribution. random_shuffle can take a particular random number generating function object rand , where rand takes a positive argument n of distance type of the RandomAccessIterator and returns a randomly chosen value between 0 and n - 1. Complexity In the random_shuffle algorithm, (last - first) -1 swaps are done. Example // // rndshufl.cpp // #include #include #include
Warning If your compiler does not support default template parameters, you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software raw_storage_iterator Memory Management Summary Enables iterator-based algorithms to store results into uninitialized memory.
Description Class raw_storage_iterator enables iterator-based algorithms to store their results in uninitialized memory. The template parameter, OutputIterator is required to have its operator* return an object for which operator& is both defined and returns a pointer to T. Constructor raw_storage_iterator (OutputIterator x); Initializes the iterator to point to the same value that x points to.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software remove Algorithm Summary Move desired elements to the front of a container, and return an iterator that describes where the sequence of desired elements ends.
designates the end of the resulting range. remove is stable, that is, the relative order of the elements that are not removed is the same as their relative order in the original range. remove does not actually reduce the size of the sequence. It actually operates by: 1) copying the values that are to be retained to the front of the sequence, and 2) returning an iterator that describes where the sequence of retained values ends.
vector::iterator result = remove(v.begin(), v.end(), 7); // delete dangling elements from the vector v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // remove everything beyond the fourth element result = remove_if(v.begin()+4, v.begin()+8, all_true()); // delete dangling elements v.erase(result, v.end()); copy(v.begin(),v.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software remove_copy Algorithm Summary Move desired elements to the front of a container, and return an iterator that describes where the sequence of desired elements ends.
#include #include #include #include template struct all_true : public unary_function { bool operator() (const Arg&) { return 1; } }; int main () { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr+0, arr+10); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // // Remove the 7. // vector::iterator result = remove(v.begin(), v.end(), 7); // // Delete dangling elements from the vector. // v.
Warning If your compiler does not support default template parameters, you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software remove_copy_if Algorithm Summary Move desired elements to the front of a container, and return an iterator that describes where the sequence of desired elements ends.
#include #include #include template struct all_true : public unary_function { bool operator() (const Arg&) { return 1; } }; int main () { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr+0, arr+10); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // // Remove the 7. // vector::iterator result = remove(v.begin(), v.end(), 7); // // Delete dangling elements from the vector. // v.erase(result, v.end()); copy(v.
Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software remove_if Algorithm Summary Move desired elements to the front of a container, and return an iterator that describes where the sequence of desired elements ends.
are not removed is the same as their relative order in the original range. remove_if does not actually reduce the size of the sequence. It actually operates by: 1) copying the values that are to be retained to the front of the sequence, and 2) returning an iterator that describes where the sequence of retained values ends. Elements that are after this iterator are simply the original sequence values, left unchanged.
// remove the 7 vector::iterator result = remove(v.begin(), v.end(), 7); // delete dangling elements from the vector v.erase(result, v.end()); copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; // remove everything beyond the fourth element result = remove_if(v.begin()+4, v.begin()+8, all_true()); // delete dangling elements v.erase(result, v.end()); copy(v.begin(),v.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software replace Algorithm Summary Substitutes elements stored in a collection with new values.
Complexity Exactly last - first comparisons or applications of the corresponding predicate are done. Example // // replace.cpp // #include #include #include #include
List List List List 1 2 3 4 5 6 7 8 9 10 after replace: 1 2 3 4 5 6 11 8 9 10 after replace_if: 13 13 13 4 5 6 11 8 9 10 using replace_copy to cout: 17 17 17 4 5 6 11 8 9 10 with all elements output as 19s: 19 19 19 19 19 19 19 19 19 19 Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software replace_copy Algorithm Summary Substitutes elements stored in a collection with new values.
#include #include #include #include template struct all_true : public unary_function { bool operator() (const Arg&) { return 1; } }; int main () { // // Initialize a vector with an array of integers. // int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; vector v(arr+0, arr+10); // // Print out original vector. // cout << "The original list: " << endl << " "; copy(v.begin(), v.
} Output : The original list: 1 2 3 4 5 6 7 8 9 10 List after replace: 1 2 3 4 5 6 11 8 9 10 List after replace_if: 13 13 13 4 5 6 11 8 9 10 List using replace_copy to cout: 17 17 17 4 5 6 11 8 9 10 List with all elements output as 19s: 19 19 19 19 19 19 19 19 19 19 Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software replace_copy_if Algorithm Summary Substitutes elements stored in a collection with new values.
#include #include #include #include template struct all_true : public unary_function { bool operator() (const Arg&) { return 1; } }; int main () { // // Initialize a vector with an array of integers. // int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; vector v(arr+0, arr+10); // // Print out original vector. // cout << "The original list: " << endl << " "; copy(v.begin(), v.
} Output : The original list: 1 2 3 4 5 6 7 8 9 10 List after replace: 1 2 3 4 5 6 11 8 9 10 List after replace_if: 13 13 13 4 5 6 11 8 9 10 List using replace_copy to cout: 17 17 17 4 5 6 11 8 9 10 List with all elements output as 19s: 19 19 19 19 19 19 19 19 19 19 Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software replace_if Algorithm Summary Substitutes elements stored in a collection with new values.
Description The replace_if algorithm replaces element referred to by iterator i in the range [first, last) with new_value when the following condition holds: pred(*i) == true. Complexity Exactly last - first applications of the predicate are done. Example // // replace.cpp // #include #include #include #include
cout << endl << endl; return 0; } Output : The original list: 1 2 3 4 5 6 7 8 9 10 List after replace: 1 2 3 4 5 6 11 8 9 10 List after replace_if: 13 13 13 4 5 6 11 8 9 10 List using replace_copy to cout: 17 17 17 4 5 6 11 8 9 10 List with all elements output as 19s: 19 19 19 19 19 19 19 19 19 19 Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software return_temporary_buffer Memory Handling Primitive Summary Pointer based primitive for handling memory Contents ● Synopsis ● Description ● See Also Synopsis #include template void return_temporary_buffer (T* p, T*); Description The return_temporary_buffer templated function returns a buffer, previously allocated through get_temporary_buffer, to available memory.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software reverse Algorithm Summary Reverse the order of elements in a collection.
Complexity reverse performs exactly (last - first)/2 swaps. Example // // reverse.cpp // #include #include #include int main() { //Initialize a vector with an array of ints int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); //Print out elements in original (sorted) order cout << "Elements before reverse: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Reverse the ordering reverse(v.begin(), v.
vector See Also reverse_copy, swap
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software reverse_bidirectional_iterator, reverse_iterator Iterator Summary An iterator that traverses a collection backwards.
This mapping is dictated by the fact that, while there is always a pointer past the end of a container, there might not be a valid pointer before its beginning. The following are true for reverse_bidirectional_iterators : ● These iterators may be instantiated with the default constructor or by a single argument constructor that initializes the new reverse_bidirectional_iterator with a bidirectional_iterator. ● operator* returns a reference to the current value pointed to.
Reference operator* (); self& operator++ (); self operator++ (int); self& operator-- (); self operator-- (int); }; // Non-member Operator template bool operator== ( const reverse_bidirectional_iterator &, const reverse_bidirectional_iterator &); template
class Reference, class Pointer, class Distance> bool operator== ( const reverse_iterator&, const reverse_iterator&); template bool operator< ( const reverse_iterator&, const reverse_iterator&); template
vector::reverse_iterator rev(v.end()); vector::reverse_iterator rev_end(v.begin()); //Output the vector backwards cout << endl << endl; cout << "Same vector, same loop, reverse_itertor: " << endl for(; rev != rev_end; rev++) cout << *rev << " "; return 0; << " } Output : Traversing vector with iterator: 3 4 7 8 Same vector, same loop, reverse_itertor: 8 7 4 3 Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software reverse_copy Algorithm Summary Reverse the order of elements in a collection while copying them to a new collecton.
#include #include int main () { // // Initialize a vector with an array of integers. // int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; vector v(arr+0, arr+10); // // Print out elements in original (sorted) order. // cout << "Elements before reverse: " << endl << " "; copy(v.begin(), v.end(), ostream_iterator(cout," ")); cout << endl << endl; // // Reverse the ordering. // reverse(v.begin(), v.end()); // // Print out the reversed elements.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software reverse_iterator See the reverse_bidirectional_iterator section of this reference.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software rotate, rotate_copy Algorithm Summary Left rotates the order of items in a collection, placing the first item at the end, second item first, etc., until the item pointed to by a specified iterator is the first item in the collection.
Description The rotate algorithm takes three iterator arguments, first, which defines the start of a sequence, last, which defines the end of the sequence, and middle which defines a point within the sequence. rotate "swaps" the segment that contains elements from first through middle-1 with the segment that contains the elements from middle through last.
#include int main() { //Initialize a vector with an array of ints int arr[10] = {1,2,3,4,5,6,7,8,9,10}; vector v(arr, arr+10); //Print out elements in original (sorted) order cout << "Elements before rotate: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); cout << endl << endl; //Rotate the elements rotate(v.begin(), v.begin()+4, v.end()); //Print out the rotated elements cout << "Elements after rotate: " << endl << " "; copy(v.begin(),v.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software search, search_n Algorithm Summary Finds a subsequence within a sequence of values that is element-wise equal to the values in an indicated range.
template search_n (ForwardIterator first, ForwardIterator last, Size count, const T& value); ForwardIterator, Size, T, BinaryPredicate> search_n (ForwardIterator first, ForwardIterator last, Size count, const T& value, BinaryPredicate pred) Description The search and search_n are used for searching for a subsequence within a sequence.
int main() { // Initialize a list sequence and // subsequence with characters char seq[40] = "Here's a string with a substring in it"; char subseq[10] = "substring"; list sequence(seq, seq+39); list subseqnc(subseq, subseq+9); //Print out the original sequence cout << endl << "The subsequence, " << subseq << ", was found at the "; cout << endl << "location identified by a '*'" << endl << " "; // Create an iterator to identify the location of // subsequence within sequence list::iterator pl
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Sequences Summary A sequence is a container that organizes a set of objects, all the same type, into a linear arrangement. vector, list, deque, and string fall into this category. Sequences offer different complexity trade-offs. vector offers fast inserts and deletes from the end of the container. deque is useful when insertions and deletions will take place at the beginning or end of the sequence.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software set Container Summary An associative container that supports unique keys. A set supports bidirectional iterators.
Description set is an associative container that supports unique keys and provides for fast retrieval of the keys. A set contains at most one of any key value. The keys are sorted using Compare. Since a set maintains a total order on its elements, you cannot alter the key values directly. Instead, you must insert new elements with an insert_iterator.
Allocator>&); allocator_type get_allocator () const; // Iterators iterator begin (); const_iterator begin () const; iterator end (); const_iterator end () const; reverse_iterator rbegin (); const_reverse_iterator rbegin () const; reverse_iterator rend (); const_reverse_iterator rend () const; // Capacity bool empty () const; size_type size () const; size_type max_size () const; // Modifiers pair insert (const value_type&); iterator insert (iterator, const value_type&); template
Constructors and Destructors explicit set (const Compare& comp = Compare(), const Allocator& alloc = Allocator ()); The default constructor. Creates a set of zero elements. If the function object comp is supplied, it is used to compare elements of the set. Otherwise, the default function object in the template argument is used. The template argument defaults to less (<). The allocator alloc is used for all storage management.
Returns an iterator that points to the past-the-end value. const_iterator end () const; Returns a const_iterator that points to the past-the-end value. reverse_iterator rbegin (); Returns a reverse_iterator that points to the past-the-end value. const_reverse_iterator rbegin () const; Returns a const_reverse_iterator that points to the past-the-end value. reverse_iterator rend (); Returns a reverse_iterator that points to the first element.
Deletes the elements in the range (first, last). Returns an iterator pointing to the element following the last deleted element, or end() if there were no elements after the deleted range. iterator find (const key_value& x) const; Returns an iterator that points to the element equal to x. If there is no such element, the iterator points to the past-the-end value. pair insert (const value_type& x); Inserts x into self according to the comparison function object.
Returns an iterator that points to the first element that is greater than or equal to x. If there is no such element, the iterator points to the past-the-end value. value_compare value_comp () const; Returns the set's comparison object. This is identical to the function key_comp(). Non-member Operators template bool operator== (const set& x, const set& y); Equality operator. Returns true if x is the same as y.
// print out the set cout << sd << endl << endl; // now let's erase half of the elements in the set int half = sd.size() >> 1; set_type::iterator sdi = sd.begin(); advance(sdi,half); sd.erase(sd.begin(),sdi); // print it out again cout << sd << endl << endl; // Make another set and an empty result set set_type sd2, sdResult; for (i = 1; i < 9; i++) sd2.insert(i+5); cout << sd2 << endl; // Try a couple of set algorithms set_union(sd.begin(),sd.end(),sd2.begin(),sd2.end(), inserter(sdResult,sdResult.
type of container as the one you are constructing (or calling a member function on), or you can use a pointer to the type of element you have in the container. For example, if your compiler does not support member function templates you can construct a set in the following two ways: int intarray[10]; set, allocator> first_set(intarray, intarray + 10); set, allocator> second_set(first_set.begin(), first_set.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software set_difference Algorithm Summary Basic set operation for sorted sequences.
OutputIterator result, Compare comp); Description The set_difference algorithm constructs a sorted difference that includes copies of the elements that are present in the range [first1, last1) but are not present in the range [first2, last2). It returns the end of the constructed range.
//Create an insert_iterator for odd insert_iterator > > odd_ins(odd, odd.begin()); //Demonstrate set_difference cout << "The result of:" << endl << "{"; copy(all.begin(),all.end(), ostream_iterator(cout," ")); cout << "} - {"; copy(even.begin(),even.end(), ostream_iterator(cout," ")); cout << "} =" << endl << "{"; set_difference(all.begin(), all.end(), even.begin(), even.end(), odd_ins); copy(odd.begin(),odd.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software set_intersection Algorithm Summary Basic set operation for sorted sequences.
OutputIterator result, Compare comp); Description The set_intersection algorithm constructs a sorted intersection of elements from the two ranges. It returns the end of the constructed range. When it finds an element present in both ranges, set_intersection always copies the element from the first range into result. This means that the result of set_intersection is guaranteed to be stable. The result of set_intersection is undefined if the result range overlaps with either of the original ranges.
copy(result.begin(),result.end(), ostream_iterator(cout," ")); cout << "}" << endl << endl; return 0; } Output : The result of: {3 5 7 8 } intersection {1 3 5 7 9 11 } = {3 5 7 } Warning If your compiler does not support default template parameters, then you need to always supply the Compare template argument and the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software set_symmetric_difference Algorithm Summary Basic set operation for sorted sequences.
set_symmetric_difference (InputIterator1 InputIterator1 InputIterator2 InputIterator2 OutputIterator first1, last1, first2, last2, result, Compare comp); Description set_symmetric_difference constructs a sorted symmetric difference of the elements from the two ranges.
//Initialize some sets int a1[] = {1,3,5,7,9,11}; int a3[] = {3,5,7,8}; set > odd(a1,a1+6), result, small(a3,a3+4); //Create an insert_iterator for result insert_iterator > > res_ins(result, result.begin()); //Demonstrate set_symmetric_difference cout << "The symmetric difference of:" << endl << "{"; copy(small.begin(),small.end(), ostream_iterator(cout," ")); cout << "} with {"; copy(odd.begin(),odd.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software set_union Algorithm Summary Basic set operation for sorted sequences.
sequences, only the element from the first sequence is copied to result. (Use the merge algorithm to create an ordered merge of two sorted sequences that contains all the elements from both sequences.) set_union assumes that the sequences are sorted using the default comparision operator less than (<), unless an alternative comparison operator (comp) is provided. Complexity At most ((last1 - first1) + (last2 - first2)) * 2 -1 comparisons are performed. Example // // set_unin.
set, allocator> instead of : set See Also includes, set, set_intersection, set_difference, set_symmetric_difference
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software sort Algorithm Summary Templated algorithm for sorting collections of entities.
partial_sort should be used. Complexity sort performs approximately NlogN, where N equals last - first, comparisons on the average. Example // // sort.cpp // #include #include #include #include struct associate { int num; char chr; associate(int n, char c) : num(n), chr(c){}; associate() : num(0), chr('\0'){}; }; bool operator<(const associate &x, const associate &y) { return x.num < y.
vector v(arr, arr+20), v1((size_t)20), v2((size_t)20); // Copy original vector to vectors #1 and #2 copy(v.begin(), v.end(), v1.begin()); copy(v.begin(), v.end(), v2.begin()); // Sort vector #1 sort(v1.begin(), v1.end()); // Stable sort vector #2 stable_sort(v2.begin(), v2.end()); // Display the results cout << "Original sort stable_sort" << endl; for(i = v.begin(), j = v1.begin(), k = v2.begin(); i != v.
instead of : vector See Also stable_sort, partial_sort, partial_sort_copy
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software sort_heap Algorithm Summary Converts a heap into a sorted collection.
Description A heap is a particular organization of elements in a range between two random access iterators [a, b). Its two key properties are: 1. *a is the largest element in the range. 2. *a may be removed by pop_heap(), or a new element added by push_heap(), in O(logN) time. These properties make heaps useful as priority queues.
copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // Now let's pop pop_heap(v1.begin(),v1.end()); pop_heap(v2.begin(),v2.end(),less()); // v1 = (3,x,y,4) and v2 = (3,x,y,4) // Copy both vectors to cout copy(v1.begin(),v1.end(),out); cout << endl; copy(v2.begin(),v2.end(),out); cout << endl; // And push push_heap(v1.begin(),v1.end()); push_heap(v2.begin(),v2.end(),less()); // v1 = (4,x,y,z) and v2 = (4,x,y,z) // Copy both vectors to cout copy(v1.begin(),v1.
Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software stable_partition Algorithm Summary 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.
group of elements that satisfy pred. In other words stable_partition returns i such that for any iterator j in the range [first, i), pred(*j) == true, and for any iterator k in the range [i, last), pred(*j) == false. The relative order of the elements in both groups is preserved. The partition algorithm can be used when it is not necessary to maintain the relative order of elements within the groups that do and do not match the predicate.
return 0; } Output : Unpartitioned values: Partitioned values: Stable partitioned values: 1 2 3 4 5 6 7 8 9 10 10 2 8 4 6 5 7 3 9 1 2 4 6 8 10 1 3 5 7 9 Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software stable_sort Algorithm Summary Templated algorithm for sorting collections of entities.
Description The stable_sort algorithm sorts the elements in the range [first, last). The first version of the algorithm uses less than (<) as the comparison operator for the sort. The second version uses the comparision function comp. The stable_sort algorithm is considered stable because the relative order of the equal elements is preserved. Complexity stable_sort does at most N(logN) **2, where N equals last -first, comparisons; if enough extra memory is available, it is NlogN. Example // // sort.
associate(-1, ' '), associate(-3, 't'), associate(23, ' '), associate(-3, 'a'), associate(-2, ' '), associate(-7, ' '), associate(-3, 'b'), associate(-8, ' '), associate(11, ' '), associate(-3, 'l'), associate(15, ' '), associate(-5, ' '), associate(-3, 'e'), associate(15, ' ')}; // Set up vectors vector v(arr, arr+20), v1((size_t)20), v2((size_t)20); // Copy original vector to vectors #1 and #2 copy(v.begin(), v.end(), v1.begin()); copy(v.begin(), v.end(), v2.begin()); // Sort vector #1 sort(v1.
<15; > <23; > <23; > Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software stack Container Adaptor Summary A container adaptor which behaves like a stack (last in, first out).
Description The stack container adaptor causes a container to behave like a "last in, first out" (LIFO) stack. The last item that was put ("pushed") onto the stack is the first item removed ("popped" off). The stack can adapt to any container that provides the operations, back(), push_back(), and pop_back(). In particular, deque , list , and vector can be used.
Allocator allocator_type get_allocator () const; Returns a copy of the allocator used by self for storage management. Member Functions bool empty () const; Returns true if the stack is empty, otherwise false. void pop (); Removes the item at the top of the stack. void push (const value_type& x); Pushes x onto the stack. size_type size () const; Returns the number of elements on the stack. value_type& top (); Returns a reference to the item at the top of the stack.
than the stack defined by the elements of y. Example // // stack.cpp // #include #include #include #include #include int main(void) { // Make a stack using a vector container stack, allocator> s; // Push a couple of values on the stack s.push(1); s.push(2); cout << s.top() << endl; // Now pop them off s.pop(); cout << s.top() << endl; s.
aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaa aaaaaaaa aaaaaaa aaaaaa aaaaa aaaa aaa aa a Warnings If your compiler does not support template parameter defaults, you are required to supply a template parameter for Container and for Allocator.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software Stream Iterators Iterators Summary Stream iterators provide iterator capabilities for ostreams and istreams. They allow generic algorithms to be used directly on streams. See the sections istream_iterator and ostream_iterator for a description of these iterators.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software string String Library Summary A specialization of the basic_string class.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software string_char_traits Summary A traits class providing types and operations to the basic_string container. Contents ● Summary ● Synopsis ● Description ● Interface ● Type ● Operations ● See Also Synopsis #include template struct string_char_traits struct string_char_traits; .
Interface template struct string_char_traits . { typedef charT char_type; static void assign (char_type&, const char_type&); . static char_type* assign (char_type*, size_t, const char_type&); static bool eq (const char_type&, const char_type&); . static bool ne (const char_type&, const char_type&); . static bool lt (const char_type&, const char_type&); . static char_type eos (); . static int compare (const char_type*, const char_type*, size_t); . static size_t length (const char_type * s); .
Return true if c1 does not equal c2. static bool lt (const char_type& c1, const char_type& c2) Return true if c1 is less than c2. static char_type eos () Return the end of string value for the the character type. Typically char_type(). static int compare (const char_type* s1, const char_type* s2, size_t n) Compare n values from s1 with n values from s2. Return 1 if s1 is greater than s2, -1 if s1 is less than s2, or 0 if they are equal.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software swap Algorithm Summary Exchange values. Contents ● Synopsis ● Description ● See Also Synopsis #include template void swap (T& a, T& b); Description The swap algorithm exchanges the values of a and b.
Click on the banner to return to the Class Reference home page.
two ranges [first, last) and [first2, first2 + (last1 - first1)) overlap. Example // // swap.cpp // #include #include int main() { int d1[] = {6, 7, 8, 9, 10, 1, 2, 3, 4, 5}; // Set up a vector vector v(d1,d1 + 10); // Output original vector cout << "For the vector: "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); // Swap the first five elements with the last five elements swap_ranges(v.begin(),v.begin()+5, v.
See Also iter_swap, swap
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software times Function Object Summary A binary function object that returns the result of multiplying its first and second arguments.
vector vec2; vector vecResult; . . . transform(vec1.begin(), vec1.end(), vecResult.begin(), times()); vec2.begin(), vec2.end(), After this call to transform, vecResult(n) will contain vec1(n) times vec2(n). Warning If your compiler does not support default template parameters, then you need to always supply the Allocator template argument.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software transform Algorithm Summary Applies an operation to a range of values in a collection and stores the result.
InputIterator2 first2, OutputIterator result, BinaryOperation binary_op); Description The transform algorithm has two forms. The first form applies unary operation op to each element of the range [first, last), and sends the result to the output iterator result. For example, this version of transform, could be used to square each element in a vector. If the output iterator (result) is the same as the input iterator used to traverse the range, transform, performs its transformation inplace.
{ //Initialize a deque with an array of ints int arr1[5] = {99, 264, 126, 330, 132}; int arr2[5] = {280, 105, 220, 84, 210}; deque d1(arr1, arr1+5), d2(arr2, arr2+5); //Print the original values cout << "The following pairs of numbers: " << endl << " "; deque::iterator i1; for(i1 = d1.begin(); i1 != d1.end(); i1++) cout << setw(6) << *i1 << " "; cout << endl << " "; for(i1 = d2.begin(); i1 != d2.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software unary_function Function Object Summary Base class for creating unary function objects. Contents ● Synopsis ● Description ● See Also Synopsis #include template struct unary_function{ typedef Arg argument_type; typedef Result result_type; }; Description Function objects are objects with an operator() defined.
unary_function class makes the task of creating templated unary function objects easier by providing the necessary typedefs for a unary function object. You can create your own unary function objects by inheriting from unary_function. See Also Function Objects, and Function Objects Section in User's Guide.
Click on the banner to return to the Class Reference home page.
Interface template class unary_negate : public unary_function { typedef typename unary_function::argument_type argument_type; typedef typename unary_function::result_type result_type; public: explicit unary_negate (const Predicate&); bool operator() (const argument_type&) const; }; template unary_negate not1 (const Predicate&); Constructor explicit u
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software uninitialized_copy Memory Management Summary An algorithms that uses the language feature placement new to copy values from one range to another location.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software uninitialized_fill Memory Management Summary Algorithm that uses the language feature placement new to set values in a collection.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software uninitialized_fill_n Memory Management Summary Algorithm that uses the language feature placement new for setting values in a collection.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software unique, unique_copy Algorithm Summary Removes consecutive duplicates from a range of values and places the resulting unique values into the result.
class OutputIterator, class BinaryPredicate> OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result, BinaryPredicate binary_pred); Description The unique algorithm moves through a sequence and eliminates all but the first element from every consecutive group of equal elements. There are two versions of the algorithm, one tests for equality, and the other tests whether a binary predicate applied to adjacent elements is true.
vector v(a1, a1+20), result; //Create an insert_iterator for results insert_iterator > ins(result, result.begin()); //Demonstrate includes cout << "The vector: " << endl << " "; copy(v.begin(),v.end(),ostream_iterator(cout," ")); //Find the unique elements unique_copy(v.begin(), v.end(), ins); //Display the results cout << endl << endl << "Has the following unique elements:" << endl << " "; copy(result.begin(),result.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software upper_bound Algorithm Summary Determines the last valid position for a value in a sorted container.
Description The upper_bound algorithm is part of a set of binary search algorithms. All of these algorithms perform binary searches on ordered containers. Each algorithm has two versions. The first version uses the less than operator (operator<) to perform the comparison, and assumes that the sequence has been sorted using that operator. The second version allows you to include a function object of type Compare, and assumes that Compare is the function used to sort the sequence.
// Try upper_bound variants iterator it3 = upper_bound(v1.begin(),v1.end(),3); // it3 = vector + 5 iterator it4 = upper_bound(v1.begin(),v1.end(),2,less()); // it4 = v1.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software value_type Type primitive Summary Determine the type of value an iterator points to.
used to instantiate the iterator. The fifth version takes and returns a T* in order to handle the case when an iterator is a simple pointer. This family of function templates can be used to extract a value type from an iterator and subsequently use that type to create a local variable.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software vector Container Summary Sequence that supports random access iterators.
Description vector is a type of sequence that supports random access iterators. In addition, it supports amortized constant time insert and erase operations at the end. Insert and erase in the middle take linear time. Storage management is handled automatically. In vector, iterator is a random access iterator referring to T. const_iterator is a constant random access iterator that returns a const T& when being dereferenced. A constructor for iterator and const_iterator is guaranteed.
explicit vector (const Allocator& = Allocator()); explicit vector (size_type, const Allocator& = Allocator ()); vector (size_type, const T&, const Allocator& = Allocator()); vector (const vector&); template vector (InputIterator, InputIterator, const Allocator& = Allocator ()); ~vector (); vector& operator= (const vector&); template void assign (InputIterator first, InputIterator last); template void
void insert (iterator, size_type, const T&); template void insert (iterator, InputIterator, InputIterator); iterator erase (iterator); iterator erase (iterator, iterator); void swap (vector&); }; // Non-member Operators template bool operator== (const vector&, const vector &); template bool operator< (const vector&, const vector&); // Specialized Algorithms template void swa
Iterators iterator begin (); Returns a random access iterator that points to the first element. const_iterator begin () const; Returns a random access const_iterator that points to the first element. iterator end (); Returns a random access iterator that points to the past-the-end value. const_iterator end () const; Returns a random access const_iterator that points to the past-the-end value. reverse_iterator rbegin (); Returns a random access reverse_iterator that points to the past-the-end value.
less one. Member Functions template void assign (InputIterator first, InputIterator last); Erases all elements contained in self, then inserts new elements from the range [first, last). template void assign (Size n, const T& t); Erases all elements contained in self, then inserts n instances of the default value of type T.
iterator erase (iterator position); Deletes the vector element pointed to by the iterator position. Returns an iterator pointing to the element following the deleted element, or end() if the deleted element was the last one in this vector. iterator erase (iterator first, iterator last); Deletes the vector elements in the range (first, last). Returns an iterator pointing to the element following the last deleted element, or end() if there were no elements in the deleted range.
pop_back (); Removes the last element of self. void push_back (const T& x); Inserts a copy of x to the end of self. void reserve (size_type n); Increases the capacity of self in anticipation of adding new elements. reserve itself does not add any new elements. After a call to reserve, capacity() is greater than or equal to n and subsequent insertions will not cause a reallocation until the size of the vector exceeds n. Reallocation does not occur if n is less than capacity().
const vector& y); Returns true if x is the same as y. template bool operator< (const vector& x, const vector& y); Returns true if the elements contained in x are lexicographically less than the elements contained in y. template void swap (vector & a, vector & b); Efficiently swaps the contents of a and b. Example // // vector.cpp // #include #include
} Output : 9 8 7 6 5 4 3 2 1 0 4 3 2 1 0 Warnings Member function templates are used in all containers provided by the Standard Template Library. An example of this feature is the constructor for vector that takes two templated iterators: template vector (InputIterator, InputIterator, const Allocator = Allocator()); vector also has an insert function of this type.
Click on the banner to return to the Class Reference home page. ©Copyright 1996 Rogue Wave Software wstring String Library Summary A specialization of the basic_string class.
Click on the banner to return to the class reference home page. Licensing Statement The Rogue Wave single-user license for this product allows a single user on a single platform to link against the product library. A site license allows a specified number of users to link against the library. The fact that both the library and this documentation are easy to copy does not make it legal to do so.