Upload
kristian-forest
View
218
Download
0
Embed Size (px)
Citation preview
8/4/2019 The Standard Library 2011 Lecture Notes
1/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.o 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 heldin balanced binary tree structure.
o Container adapters:
stackLIFO queue FIFO
priority_queue returns element with highest priority.o String:
string: Character strings and manipulation
rope: String storage and manipulationo 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 veryfast.[2] 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.
Simple example of storing STL strings in a vector.
#include #include #include using namespace std;
main(){
vector SS;
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html#VECTORhttp://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html#LISThttp://www.yolinux.com/TUTORIALS/CppStlMultiMap.htmlhttp://www.yolinux.com/TUTORIALS/CppStlMultiMap.html#MULTIMAPhttp://www.yolinux.com/TUTORIALS/CppStlMultiMap.html#MULTIMAPhttp://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.htmlhttp://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html#VECTORhttp://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html#LISThttp://www.yolinux.com/TUTORIALS/CppStlMultiMap.htmlhttp://www.yolinux.com/TUTORIALS/CppStlMultiMap.html#MULTIMAPhttp://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.html8/4/2019 The Standard Library 2011 Lecture Notes
2/13
SS.push_back("The number is 10");SS.push_back("The number is 20");SS.push_back("The number is 30");cout
8/4/2019 The Standard Library 2011 Lecture Notes
3/13
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. Forexample, 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 alot 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 anelement in a vector or a deque. To include the class definition use: #include
// Standard Template Library example#include #include using namespace std;// Simple example uses type intmain(){
list L;L.push_back(0); // Insert a new element at the endL.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::iterator i;for(i=L.begin(); i != L.end(); ++i) cout
8/4/2019 The Standard Library 2011 Lecture Notes
4/13
The term deque (it rhymes with "check" [3] ) is an abbreviation for "double-ended queue." It is adynamic 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
// stl/deque1.cpp
#include
#include using namespace std;int main(){
deque coll; //deque container for floating-point elements //insert elements from 1.1 to 6.6 each at the front
for (int i=1; i
8/4/2019 The Standard Library 2011 Lecture Notes
5/13
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 standardpointers 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 usingoperator- -.
Operators == and !=
Return whether two iterators represent the same position.
Operator =
Assigns an iterator (the position of the element to which it refers).
vector myVec;
vector::iterator first, last;
for ( long i=0; i= myVec.end() )
return;myVec.erase( first, last );
// stl/list2.cpp using ITERATOR
#include #include using namespace std;int main()
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 ofinterest, and we test this element against
the return value of end (which give an
iterator one past the last valid item in acollection). 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.
8/4/2019 The Standard Library 2011 Lecture Notes
6/13
{list coll; //list container for character elements
// append elements from 'a' to 'z'for (char c='a'; c
8/4/2019 The Standard Library 2011 Lecture Notes
7/13
8/4/2019 The Standard Library 2011 Lecture Notes
8/13
erase()
clear()
Erase all elements of vector.
Declaration: void clear()
erase(iterator)erase(begin_iterator,end_iterator)
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
8/4/2019 The Standard Library 2011 Lecture Notes
9/13
Iterator methods/operators:
Method/operator Description
begin() Return iterator to first element of vector.
Declaration: const_iterator begin() const
end() Return iterator to end of vector (not last element of vector but past last element)
Declaration: const_iterator end() const
rbegin() Return iterator to first element of vector (reverse order).
Declaration: const_reverse_iterator rbegin() const
rend() 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 Effect
ContTypec Creates an empty container without any element
ContTypec1(c2) Copies a container of the same type
ContTypec(beg,end) Creates a container and initializes it with copies of all elements of[beg,end)
c.~ContType() Deletes all elements and frees the memory
c.size() Returns the actual number of elements
c.empty() Returns whether the container is empty (equivalent to size()==0, but might be faster)
c.max_size() Returns the maximum number of elements possible
c1 == 2 Returns whetherc1 is equal to c2
c1 != c2 Returns whetherc1 is not equal to c2 (equivalent to !(c1==c2))c1 < c2 Returns whetherc1 is less than c2
c1 > c2 Returns whetherc1 is greater than c2 (equivalent to c2
8/4/2019 The Standard Library 2011 Lecture Notes
10/13
c.size() Returns the actual number of elements
c.empty() Returns whether the container is empty (equivalent to size()==0, but might be faster)
c.max_size() Returns the maximum number of elements possible
capacity() Returns the maximum possible number of elements without reallocation
reserve() Enlarges capacity, if not enough yet[7]
c1 == c2 Returns whetherc1 is equal to c2
c1 != c2 Returns whetherc1 is not equal to c2 (equivalent to !(c1==c2))
c1 < c2 Returns whetherc1 is less than c2
c1 > c2 Returns whetherc1 is greater than c2 (equivalent to c2
8/4/2019 The Standard Library 2011 Lecture Notes
11/13
c.clear() Removes all elements (makes the container empty)
Constructors and Destructor of Deques
Operation Effect
deque c Creates an empty deque without any elements
deque c1(c2) Creates a copy of another deque of the same type (all elements are copied)
deque c(n) Creates a deque with n elements that are created by the default constructor
deque c(n,elem) Creates a deque initialized with n copies of element elem
deque c(beg,end) Creates a deque initialized with the elements of the range [beg,end)
c.~deque() Destroys all elements and frees the memory
Nonmodifying Operations of Deques
Operation Effect
c.size() Returns the actual number of elements
c.empty () Returns whether the container is empty (equivalent to size()==0, but might be faster)
c.max_size() Returns the maximum number of elements possible
c1 == c2 Returns whetherc1 is equal to c2
c1 != c2 Returns whetherc1 is not equal to c2 (equivalent to ! (c1==c2))
c1 < c2 Returns whetherc1 is less than c2
c1 > c2 Returns whetherc1 is greater than c2 (equivalent to c2
8/4/2019 The Standard Library 2011 Lecture Notes
12/13
c.push_front (elem) Inserts a copy ofelem at the beginning
c.pop_front() Removes the first element (does not return it)
c.erase(pos) Removes the element at iterator position pos and returns the position of the next element
c.erase (beg,end) Removes all elements of the range [beg,end) and returns the position of the next element
c. resize (num) Changes the number of elements to num (ifsize () grows, new elements are created by their defaul
constructor)
c.resize (num, elem) Changes the number of elements to num (ifsize () grows, new elements are copies ofelem)
c.clear() Removes all elements (makes the container empty)
Constructors and Destructor of Lists
Operation Effect
list c Creates an empty list without any elements
list c1(c2) Creates a copy of another list of the same type (all elements are copied)
list c(n) Creates a list with n elements that are created by the default constructor
list c(n,elem) Creates a list initialized with n copies of element elem
list c (beg,end) Creates a list initialized with the elements of the range [beg,end)
c.~list() Destroys all elements and frees the memory
Nonmodifying Operations of Lists
Operation Effect
c.size() Returns the actual number of elements
c. empty () Returns whether the container is empty (equivalent to size()==0, but might be faster)
c.max_size() Returns the maximum number of elements possible
c1 == c2 Returns whetherc1 is equal to c2
c1 != c2 Returns whetherc1 is not equal to c2 (equivalent to !(c1==c2))
c1 < c2 Returns whetherc1 is less than c2
c1 > c2 Returns whetherc1 is greater than c2 (equivalent to c2
8/4/2019 The Standard Library 2011 Lecture Notes
13/13
c.insert (pos, elem) Inserts at iterator position pos a copy ofelem and returns the position of the new element
c.insert (pos,n, elem) Inserts at iterator position pos n copies ofelem (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) Appends a copy ofelem at the end
c.pop_back() Removes the last element (does not return it)
c.push_front(elem) Inserts a copy ofelem at the beginning
c.pop_front () Removes the first element (does not return it)c. remove (val) Removes all elements with value val
c.remove_if (op) Removes all elements for which op(elem) yields true
c. erase (pos) Removes the element at iterator position pos and returns the position of the next element
c.erase (beg,end) Removes all elements of the range [beg,end) and returns the position of the next element
c. resize (num) Changes the number of elements to num (ifsize() grows, new elements are created by their
default constructor)
c.resize (num, elem) Changes the number of elements to num (ifsize ( ) grows, new elements are copies ofelem)
c. clear () Removes all elements (makes the container empty)