Sunteți pe pagina 1din 13

The Standard Library is a fundamental part of the C++ Standard.

It provides C++ programmers with a comprehensive set of efficiently implemented tools and facilities that can be used for most types of applications. STL's are a set of C++ template classes to provide common programming data structures and functions such as doubly linked lists (list), paired arrays (map), expandable arrays (vector), large string storage and manipulation (rope), etc. For any particular application, several different STL containers might be appropriate. Select the most appropriate container that achieves the best performance STL can be categorized into the following groupings:

Container classes:
o

Sequences: vector: Dynamic array of variables, struct or objects. Insert data at the end. deque: Array which supports insertion/removal of elements at beginning or end of array list: Linked list of variables, struct or objects. Insert/remove anywhere. Associative Containers: set (duplicate data not allowed in set), multiset (duplication allowed): Collection of ordered data in a balanced binary tree structure. Fast search. map (unique keys), multimap (duplicate keys allowed): Associative key-value pair held in balanced binary tree structure. Container adapters: stack LIFO queue FIFO priority_queue returns element with highest priority. String: string: Character strings and manipulation rope: String storage and manipulation bitset: Contains a more intuitive method of storing and manipulating bits.

Operations/Utilities:
iterator: (examples in this tutorial) STL class to represent position in an STL container. An iterator is declared to be associated with a single container class type. algorithm: Routines to find, count, sort, search, ... elements in container classes auto_ptr: Class to manage memory pointers and avoid memory leaks.

STL vector: Dynamic array of variables, struct or objects. Insert data at the end.
A vector manages its elements in a dynamic array. It enables random access, which means you can access each element directly with the corresponding index. Appending and removing elements at the end of the array is very fast. However, inserting an element in the middle or at the beginning of the array takes time because all the following elements have to be moved to make room for it while maintaining the order.
[2]

Simple example of storing STL strings in a vector.


#include <iostream> #include <vector> #include <string> using namespace std; main() { vector<string> SS;

SS.push_back("The number is 10"); SS.push_back("The number is 20"); SS.push_back("The number is 30"); cout << "Loop by index:" << endl; int ii; for(ii=0; ii < SS.size(); ii++) { cout << SS[ii] << endl; } cout << endl << "Constant Iterator:" << endl; vector<string>::const_iterator cii; for(cii=SS.begin(); cii!=SS.end(); cii++) { cout << *cii << endl; } cout << endl << "Reverse Iterator:" << endl; vector<string>::reverse_iterator rii; for(rii=SS.rbegin(); rii!=SS.rend(); ++rii) { cout << *rii << endl; } cout << endl << "Sample Output:" << endl; cout << SS.size() << endl; cout << SS[2] << endl; swap(SS[0], SS[2]); cout << SS[2] << endl; }//end of main()

Output:
Loop by index: The number is 10 The number is 20 The number is 30 Constant Iterator: The number is 10 The number is 20 The number is 30 Reverse Iterator: The number is 30 The number is 20 The number is 10 Sample Output: 3 The number is 30 The number is 10

// stl/vector1.cpp #include <iostream> #include <vector> using namespace std; int main() { vector<int> coll;

//vector container for integer elements

// append elements with values 1 to 6 for (int i=1; i<=6; ++i) { coll.push_back(i); } //print all elements followed by a space for (int i=0; i<coll.size( ); ++i) { cout << coll[i] << ' '; } cout << endl; }

STL list: Linked list of variables, struct or objects. Insert/remove anywhere. A collection of elements of type
T. The collection is stored as a bi-directional linked list of elements, each containing a member of type T.

A list is implemented as a doubly linked list of elements. This means each element in a list has its own segment of memory and refers to its predecessor and its successor. Lists do not provide random access. For example, to access the tenth element, you must navigate the first nine elements by following the chain of their links. However, a step to the next or previous element is possible in constant time. Thus, the general access to an arbitrary element takes linear time (the average distance is proportional to the number of elements). This is a lot worse than the amortized constant time provided by vectors and deques. The advantage of a list is that the insertion or removal of an element is fast at any position. Only the links must be changed. This implies that moving an element in the middle of a list is very fast compared with moving an element in a vector or a deque. To include the class definition use: #include <list>
// Standard Template Library example #include <iostream> #include <list> using namespace std; // Simple example uses type int main() { list<int> L; L.push_back(0); // Insert a new element at the end L.push_front(0); // Insert a new element at the beginning L.insert(++L.begin(),2); // Insert "2" before position of first argument // (Place before second argument) L.push_back(5); L.push_back(6); list<int>::iterator i; for(i=L.begin(); i != L.end(); ++i) cout << *i << " "; cout << endl; return 0; }

// stl/list1.cpp #include <iostream> #include <list> using namespace std; int main() { list<char> coll;

//list container for character elements

// append elements from 'a' to 'z' for (char c='a'; c<= ' z '; ++c) { coll.push_back(c); } /* print all elements * - while there are elements * - print and remove the first element */ while (! coll.empty()) { cout << coll.front() << ' '; coll.pop_front(); } cout << endl;

deque A collection of varying length of elements of type T. The sequence is represented in a way that permits insertion and removal of an element at either end with a single element copy, and supports insertion and removal anywhere in the sequence, but a sequence copy follows each operation.

The term deque (it rhymes with "check" [3] ) is an abbreviation for "double-ended queue." It is a dynamic array that is implemented so that it can grow in both directions. Thus, inserting elements at the end and at the beginning is fast. However, inserting elements in the middle takes time because elements must be moved. To include the class definition use: #include <deque>
// stl/deque1.cpp #include <iostream> #include <deque> using namespace std; int main() { deque<float> coll; //deque container for floating-point elements //insert elements from 1.1 to 6.6 each at the front for (int i=1; i<=6; ++i) { coll.push_front(i*1. 1); //insert at the front } //print all elements followed by a space for (int i=0; i<coll.size(); ++i) { cout << coll[i] << ' '; } cout << endl; }

map A collection for a varying length sequence of elements of type pair<const Key, T>. The first element of each pair is the sort key and the second is its associated value. The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element. The key can be a simple as a number or string or as complex a key class. The key class must support normal comparison operations so that the collection can be sorted or searched. To include the class definition use: #include <map> multimap A collection of a varying length sequence of elements of type pair<const Key, T>. The first element of each pair is the sort key and the second is its associated value. The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element. To include the class definition use: #include <map> set A collection that controls a varying length sequence of elements of type const Key. Each element serves as both a sort key and a value. The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element. To include the class definition use: #include <set> multiset A collection of a varying-length sequence of elements of type const Key. Each element serves as both a sort key and a value. The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element. To include the class definition use: #include <set>

Iterators
Iterators support the access of elements in a collection. They are used throughout the STL to access and list elements in a container. The iterators for a particular collection are defined in the collection class definition. Below we list three types of iterators, iterator, reverse_iterator, and random access. Random

access iterators are simply iterators that can go both forward and backward through a collection with any step value. STL iterators, which have properties similar to those of pointers, are used by programs to manipulate the STL-container elements. In fact, standard arrays can be manipulated as STL containers, using standard pointers as iterators. We will see that manipulating containers with iterators is convenient and provides tremendous expressive power when combined with STL algorithmsin some cases, reducing many lines of code to a single statement. An iterator is an object that can "iterate" (navigate) over elements. These elements may be all or part of the elements of a STL container. An iterator represents a certain position in a container. The following fundamental operations define the behavior of an iterator:

Operator * Returns the element of the actual position. If the elements have members, you can use operator -> to access those members directly from the iterator.
[5]

Operator ++ Lets the iterator step forward to the next element. Most iterators also allow stepping backward by using operator - -.

Operators == and != Return whether two iterators represent the same position.

Operator = Assigns an iterator (the position of the element to which it refers).

vector<int>

myVec; first, last;

vector<int>::iterator

for ( long i=0; i<10; i++ ) myVec.push_back(i); first = myVec.begin(); last = myVec.begin() + 5; if ( last >= myVec.end() ) return; myVec.erase( first, last );

This code will erase the first five elements of the vector. Note, we are setting the last iterator to one past the last element we of interest, and we test this element against the return value of end (which give an iterator one past the last valid item in a collection). Always remember when using STL, to mark the end of an operation use an iterator that points to the next element after the last valid element in the operation.

// stl/list2.cpp using ITERATOR #include <iostream> #include <list> using namespace std; int main()

list<char> coll;

//list container for character elements

// append elements from 'a' to 'z' for (char c='a'; c<='z'; ++c) { coll.push_back(c); } /*print all elements * - iterate over all elements */ list<char>::const_iterator pos; for (pos = coll.begin(); pos != coll.end(); ++pos) { cout << *pos << ' ' ; } cout << endl; }

Algorithms
Up to this point we have discussed how to use STL at a bare minimum, now we need to delve into the most important part of the collections. How do we manipulate a collection? For example, if we had list of strings, what would we need to sort the list in alphabetical order, or if we wanted to search a collection for a set of elements that matched a given criterion. This is where STL algorithms are used. In your visual studio installation, under include directory, you will find an include file, algorithm. In algorithm a set of template based functions are declared. These functions can be used to manipulate STL collections. The functions can be categorized in the following: sequence, sorting and numeric. STL algorithms are functions that perform such common data manipulations as searching, sorting and comparing elements (or entire containers). Approximately 70 algorithms are implemented in the STL. Most of them use iterators to access container elements. Each algorithm has minimum requirements for the types of iterators that can be used with it. We will see that each first-class container supports specific iterator types, some more powerful than others. A container's supported iterator type determines whether the container can be used with a specific algorithm. Iterators encapsulate the mechanism used to access container elements. This encapsulation enables many of the STL algorithms to be applied to several containers without regard for the underlying container implementation. As long as a container's iterators support the minimum requirements of the algorithm, then the algorithm can process that container's elements. This also enables programmers to create new algorithms that can process the elements of multiple container types. Standard Library container class Description Sequence containers
vector deque list

rapid insertions and deletions at back direct access to any element rapid insertions and deletions at front or back direct access to any element doubly linked list, rapid insertion and deletion anywhere

Associative containers
set multiset map

rapid lookup, no duplicates allowed rapid lookup, duplicates allowed one-to-one mapping, no duplicates allowed, rapid key-based lookup

Standard Library container class Description


multimap

one-to-many mapping, duplicates allowed, rapid key-based lookup

Container adapters
stack queue priority_queue

last-in, first-out (LIFO) first-in, first-out (FIFO) highest-priority element is always the first element out

Constructor/Declaration:
Method/operator vector<T> v; vector<T> v(size_type n); vector<T> v(size_type n,const T& t); Description Vector declaration of data type "T". Declaration of vector containing type "T" and of size "n" (quantity). Declaration of vector containing type "T", of size "n" (quantity) containing value "t". Declaration: vector(size_type n, const T& t) Copy of Vector of data type "T" and range begin_iterator to end_iterator. Declaration: template vector(InputIterator,
InputIterator)

vector<T> v(begin_iterator,end_iterator);

Size methods/operators:
Method/operator empty() size() resize(n, t=T()) capacity() reserve(size_t n) max_size() Description Returns bool (true/false). True if empty. Declaration: bool empty() const Number of elements of vector. Declaration: size_type size() const Adjust by adding or deleting elements of vector so that its size is "n". Declaration: void resize(n, t = T()) Max number of elements of vector before reallocation. Declaration: size_type capacity() const Max number of elements of vector set to "n" before reallocation. Declaration: void reserve(size_t) Max number of elements of vector possible. Declaration: size_type max_size() const

Note: size_type is an unsigned integer.

Other methods/operators:
Method/operator Description

erase() clear() erase(iterator) erase(begin_iterator,end_iterator)

Erase all elements of vector. Declaration: void clear() Erase element of vector. Returns iterator to next element. Erase element range of vector. Returns iterator to next element. Declarations:
iterator erase(iterator pos) iterator erase(iterator first, iterator last)

= Example: X=Y() <

Assign/copy entire contents of one vector into another. Declaration: vector& operator=(const vector&) Comparison of one vector to another. Declaration: bool operator<(const vector&, const
vector&)

==

Returns bool. True if every element is equal. Declaration: bool operator==(const vector&, const
vector&)

at(index) v[index] front() v[0] back() push_back(const T& value) pop_back() assign(size_type n,const T& t) assign(begin_iterator,end_iterator) insert(iterator, const T& t) insert(iterator pos, size_type n, const T& x)

Element of vector. Left and Right value assignment: v.at(i)=e; and e=v.at(i); Declaration: reference operator[](size_type n) First element of vector. (Left and Right value assignment.) Declaration: reference front() Last element of vector. (Left and Right value assignment.) Declaration: reference back() Add element to end of vector. Declaration: void push_back(const T&) Remove element from end of vector. Declaration: void pop_back() Assign first n elements a value "t". Replace data in range defined by iterators. Declaration: Insert at element "iterator", element of value "t". Declaration: iterator insert(iterator pos, const T& x) Starting before element "pos", insert first n elements of value "x". Declaration: void insert(iterator pos, size_type n,
const T& x)

insert(iterator pos, begin_iterator,end_iterator)

Starting before element "pos", insert range begin_iterator to end_iterator. Declaration: void insert(iterator pos, InputIterator
f, InputIterator l)

swap(vector& v2)

Swap contents of two vectors. Declaration: void swap(vector&)

Iterator methods/operators:
Method/operator begin() end() rbegin() rend() ++ -Description Return iterator to first element of vector. Declaration: const_iterator begin() const Return iterator to end of vector (not last element of vector but past last element) Declaration: const_iterator end() const Return iterator to first element of vector (reverse order). Declaration: const_reverse_iterator rbegin() const Return iterator to end of vector (not last element but past last element) (reverse order). Declaration: const_reverse_iterator rend() const Increment iterator. Decrement iterator.

Common Operations of Container Classes Operation ContType c ContType c1(c2) ContType c(beg,end) c. ContType() c.size() c.empty() c.max_size() c1 == 2 c1 != c2 c1 < c2 c1 > c2 c1 <= c2 c1 >= c2 c1 = c2 c1.swap(c2) swap(c1,c2) c.begin() c.end() c.rbegin() c.rend() c.erase(beg,end) c.clar() c.get_allocator()
~

Effect Creates an empty container without any element Copies a container of the same type Creates a container and initializes it with copies of all elements of [beg,end) Deletes all elements and frees the memory Returns the actual number of elements Returns whether the container is empty (equivalent to size()==0, but might be faster) Returns the maximum number of elements possible Returns whether c1 is equal to c2 Returns whether c1 is not equal to c2 (equivalent to !(c1==c2)) Returns whether c1 is less than c2 Returns whether c1 is greater than c2 (equivalent to c2<c1 Returns whether c1 is less than or equal to c2 (equivalent to !(c2<c1)) Returns whether c1is greater than or equal to c2 (equivalent to !(c1<c2)) Assigns all elements of c1 to c2 Swaps the data of c1and c2 Same (as global function) Returns an iterator for the first element Returns an iterator for the position after the last element Returns a reverse iterator for the first element of a reverse iteration Returns a reverse iterator for the position after the last element of a reverse iteration Removes all elements of the range [beg,end) (some containers return next element not removed) Removes all elements (makes the container empty) Returns the memory model of the container Nonmodifying Operations of Vectors

c.insert(pos,elem) Inserts a copy of elem (return value and the meaning of pos differ)

Operation

Effect

c.size() c.empty() c.max_size() capacity() reserve() c1 == c2 c1 != c2 c1 < c2 c1 > c2 c1 <= c2 c1 >= c2

Returns the actual number of elements Returns whether the container is empty (equivalent to size()==0, but might be faster) Returns the maximum number of elements possible Returns the maximum possible number of elements without reallocation Enlarges capacity, if not enough yet[7] Returns whether c1 is equal to c2 Returns whether c1 is not equal to c2 (equivalent to ! (c1==c2)) Returns whether c1 is less than c2 Returns whether c1 is greater than c2 (equivalent to c2<c1) Returns whether c1 is less than or equal to c2 (equivalent to ! (c2<c1)) Returns whether c1 is greater than or equal to c2 (equivalent to ! (c1<c2)) Assignment Operations of Vectors

Operation c1 = c2 c.assign(n,elem) c.assign(beg,end) c1.swap(c2) swap(c1,c2) Operation c.at(idx) c[idx] c.front() c.back()

Effect Assigns all elements of c2 to c1 Assigns n copies of element elem Assigns the elements of the range [beg,end) Swaps the data of c1 and c2 Same (as global function) Direct Element Access of Vectors Effect Returns the element with index idx (throws range error exception if idx is out of range) Returns the element with index idx (no range checking) Returns the first element (no check whether a first element exists) Returns the last element (no check whether a last element exists) Iterator Operations of Vectors

Operation c.begin() c.end() c.rbegin() c.rend()

Effect Returns a random access iterator for the first element Returns a random access iterator for the position after the last element Returns a reverse iterator for the first element of a reverse iteration Returns a reverse iterator for the position after the last element of a reverse iteration Insert and Remove Operations of Vectors

Operation c.insert(pos,elem)

Effect Inserts at iterator position pos a copy of elem and returns the position of the new element

c.insert(pos,n,elem) Inserts at iterator position pos n copies of elem (returns nothing) c.insert(pos,beg,end) Inserts at iterator position pos a copy of all elements of the range [beg,end) (returns nothing) c.push_back(elem) c.pop_back() c.erase(pos) c.erase(beg,end) c.resize(num) c.resize(num,elem) Appends a copy of elem at the end Removes the last element (does not return it) Removes the element at iterator position pos and returns the position of the next element Removes all elements of the range [beg,end) and returns the position of the next element Changes the number of elements to num (if size() grows, new elements are created by their default constructor) Changes the number of elements to num (if size() grows, new elements are copies of elem)

c.clear()

Removes all elements (makes the container empty) Constructors and Destructor of Deques

Operation deque<Elem> c deque<Elem> c1(c2) deque<Elem> c(n) deque<Elem> c(n,elem) deque<Elem> c(beg,end) c. deque<Elem>()
~

Effect Creates an empty deque without any elements Creates a copy of another deque of the same type (all elements are copied) Creates a deque with n elements that are created by the default constructor Creates a deque initialized with n copies of element elem Creates a deque initialized with the elements of the range [beg,end) Destroys all elements and frees the memory Nonmodifying Operations of Deques

Operation c.size() c.empty () c.max_size() c1 == c2 c1 != c2 c1 < c2 c1 > c2 c1 <= c2 c1 >= c2 c.at(idx) c[idx] c.front() c.back() c.begin() c.end() c.rbegin() c.rend()

Effect Returns the actual number of elements Returns whether the container is empty (equivalent to size()==0, but might be faster) Returns the maximum number of elements possible Returns whether c1 is equal to c2 Returns whether c1 is not equal to c2 (equivalent to ! (c1==c2)) Returns whether c1 is less than c2 Returns whether c1 is greater than c2 (equivalent to c2<c1) Returns whether c1 is less than or equal to c2 (equivalent to ! (c2<c1) ) Returns whether c1 is greater than or equal to c2 (equivalent to ! (c1<c2) ) Returns the element with index idx (throws range error exception if idx is out of range) Returns the element with index idx (no range checking) Returns the first element (no check whether a first element exists) Returns the last element (no check whether a last element exists) Returns a random access iterator for the first element Returns a random access iterator for the position after the last element Returns a reverse iterator for the first element of a reverse iteration Returns a reverse iterator for the position after the last element of a reverse iteration Modifying Operations of Deques

Operation c1 = c2 c.assign (n,elem) c.assign (beg,end) c1.swap(c2) swap(c1,c2) c.insert (pos,elem) c. insert (pos,n,elem) c.insert (pos,beg,end) c.push_back (elem) c.pop_back()

Effect Assigns all elements of c2 to c1 Assigns n copies of element elem Assigns the elements of the range [beg,end) Swaps the data of c1 and c2 Same (as global function) Inserts at iterator position pos a copy of elem and returns the position of the new element Inserts at iterator position pos n copies of elem (returns nothing) Inserts at iterator position pos a copy of all elements of the range [beg,end) (returns nothing) Appends a copy of elem at the end Removes the last element (does not return it)

c.push_front (elem) c.pop_front() c.erase(pos) c.erase (beg,end) c. resize (num)

Inserts a copy of elem at the beginning Removes the first element (does not return it) Removes the element at iterator position pos and returns the position of the next element Removes all elements of the range [beg,end) and returns the position of the next element Changes the number of elements to num (if size () grows, new elements are created by their default constructor) Removes all elements (makes the container empty) Constructors and Destructor of Lists

c.resize (num, elem) Changes the number of elements to num (if size () grows, new elements are copies of elem) c.clear()

Operation list<Elem> c list<Elem> c1(c2) list<Elem> c(n) list<Elem> c(n,elem) list<Elem> c (beg,end) c. list<Elem>()
~

Effect Creates an empty list without any elements Creates a copy of another list of the same type (all elements are copied) Creates a list with n elements that are created by the default constructor Creates a list initialized with n copies of element elem Creates a list initialized with the elements of the range [beg,end) Destroys all elements and frees the memory Nonmodifying Operations of Lists

Operation c.size() c. empty () c.max_size() c1 == c2 c1 != c2 c1 < c2 c1 > c2 c1 <= c2 c1 >= c2

Effect Returns the actual number of elements Returns whether the container is empty (equivalent to size()==0, but might be faster) Returns the maximum number of elements possible Returns whether c1 is equal to c2 Returns whether c1 is not equal to c2 (equivalent to ! (c1==c2)) Returns whether c1 is less than c2 Returns whether c1 is greater than c2 (equivalent to c2<c1) Returns whether c1 is less than or equal to c2 (equivalent to ! (c2<c1) ) Returns whether c1 is greater than or equal to c2 (equivalent to ! (c1<c2)) Assignment Operations of Lists Operation Effect Assigns all elements of c2 to c1 Assigns n copies of element elem Assigns the elements of the range [beg,end) Swaps the data of c1 and c2 Same (as global function) Direct Element Access of Lists

c1 = c2 c.assign(n,elem) c.assign(beg,end) c1.swap(c2) swap(c1,c2)

Operation c.front() c.back()

Effect Returns the first element (no check whether a first element exists) Returns the last element (no check whether a last element exists) Insert and Remove Operations of Lists

Operation

Effect

c.insert (pos, elem) c. insert (pos, beg,end) c.push_back(elem) c.pop_back() c.push_front(elem) c.pop_front () c. remove (val) c.remove_if (op) c. erase (pos) c.erase (beg,end) c. resize (num) c.resize (num, elem) c. clear ()

Inserts at iterator position pos a copy of elem and returns the position of the new element Inserts at iterator position pos a copy of all elements of the range [beg,end) (returns nothing) Appends a copy of elem at the end Removes the last element (does not return it) Inserts a copy of elem at the beginning Removes the first element (does not return it) Removes all elements with value val Removes all elements for which op(elem) yields true Removes the element at iterator position pos and returns the position of the next element Removes all elements of the range [beg,end) and returns the position of the next element Changes the number of elements to num (if size() grows, new elements are created by their default constructor) Changes the number of elements to num (if size ( ) grows, new elements are copies of elem) Removes all elements (makes the container empty)

c.insert (pos,n, elem) Inserts at iterator position pos n copies of elem (returns nothing)

S-ar putea să vă placă și