Download presentation
Presentation is loading. Please wait.
Published byElwin McBride Modified over 9 years ago
1
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Intro to the C++ Std Library
2
©Fraser Hutchinson & Cliff Green Major Components STL subset – containers, algorithms, iterators, function objects Strings – regular and wide char Numerics – complex type, valarray Streams – iostream, stream buffer Internationalization – locales, facets Utilities – auto_ptr, pair, numeric limits, min / max, allocators, bitset
3
©Fraser Hutchinson & Cliff Green Standard Template Library Subset of the C++ library comprised of containers, algorithms, iterators, and function objects Algorithms operate on ranges of elements, typically within a container or stream Iterators provide the “glue” and abstraction layer between containers and algorithms Function objects allow algorithms and certain containers to be highly customizable
4
©Fraser Hutchinson & Cliff Green STL Part of the ANSI / ISO C++ standard Created by Stepanov and Lee (originally at HP) Platform and compiler independent Avoid reinventing the wheel - STL provides type- safe implementations of –Many popular data structures as containers –Many popular algorithms to process the data in those containers STL is flexible, tested, debugged, and robust!
5
©Fraser Hutchinson & Cliff Green STL STL is extensible and customizable without inheritance STL abstraction does not mean inefficiency –Much of STL is implemented as inline –Pointers in containers are type-safe but share instantiation, saving code space
6
©Fraser Hutchinson & Cliff Green Std Lib Headers All are wrapped in the standard namespace, std #include // C++ string facilities #include // iostream facilities #include // istream class #include // ostream class #include // stream manipulators #include // ifstream, ofstream facilities #include // stringstream facilities #include // exception handling classes
7
©Fraser Hutchinson & Cliff Green Std Lib Headers (cont) #include // C++ complex class #include // numeric and type limits #include // C++ locale facilities #include // allocator and auto_ptr #include // pair class, relational ops #include // bit manipulation class #include // RTTI facilities #include // ‘new’ operator overloading #include // high performance arrays (STL headers are listed later)
8
©Fraser Hutchinson & Cliff Green Simple Input and Output std::cout - global object of type std::ostream for output streaming std::ostream - class that defines output (insertion operator) for all built-in and library types std::cin - global object of type std::istream for input streaming std::istream – class that defines input (extraction operator) for all built-in and library types
9
©Fraser Hutchinson & Cliff Green Ye Olde Example When using the standard library, every access must be either explicitly qualified with std or by using the using-directive or using-declaration. #include #include using std::cout; using std::endl; int main() { std::string const hi ("Hello world“); cout << hi << endl; return 0; }
10
©Fraser Hutchinson & Cliff Green Backwards Compatibility Standard headers in the form –Pre-standard C++ headers have.h extension (e.g. iostream.h). Use only if backwards compatibility is a requirement. C library headers have standard C++ versions, renamed by prepending a ‘c’ – is now
11
©Fraser Hutchinson & Cliff Green Differences in C Lib Headers The traditional C library functions are not all const-correct: –#include // C lib string facilities char * strchr(const char *ptr, int c); –return value points to position in ptr, and has been replaced with –#include // now in std namespace const char * strchr(const char *ptr, int c);
12
©Fraser Hutchinson & Cliff Green The String Class header defines std::string, a string class with a rich set of string construction, concatenation, searching, and substring methods ‘C’ string interface mechanisms (zero terminated character arrays) are provided String objects more convenient, flexible, safer (string logic is encapsulated within the class), and potentially more efficient than C strings, depending on usage
13
©Fraser Hutchinson & Cliff Green String Class Usage Considerations A given string implementation may not always be the best solution for your needs. There are tradeoffs between time and space, storage approaches, sharing mechanisms, copying strategies, and thread safety. –We need to have a certain amount of knowledge of an implementation.
14
©Fraser Hutchinson & Cliff Green Details Std library header actually defines a template class named std::basic_string std::string declaration is a typedef which instantiates std::basic_string with standard parameters for traditional char -based strings No restriction on what can be stored in a string – in particular, binary 0’s can be stored and will not be interpreted as the end of string
15
©Fraser Hutchinson & Cliff Green Accessing the C String in std::string has the member c_str(), returns a const pointer to a zero terminated array of chars; a non-zero terminated character pointer is returned by the data() method. // appropriate includes and using declarations int main() { string my_string (“Bubba”); char const * c_string (my_string.c_str()); cout << c_string << endl; }
16
©Fraser Hutchinson & Cliff Green C and C++ String Differences In C++, a quoted string literal is an array of characters, of type char const * Many functions take a string by const reference: int f (std::string const &); If a string literal is passed in, an implicit construction will occur: int x = f (“howdy”); // create string from const char* Standard C++ does not allow binding reference to unnamed temporary (older compilers may allow): int f (std::string &); // error if called with f(“howdy”);
17
©Fraser Hutchinson & Cliff Green Containers Typed collections of objects Provides type-safe implementations of common data structures: –linked list, array, stack, associative array, etc Algorithms are included to operate on the data in the containers: –sort, find, etc Uniform interface for all containers std::string is a special form of a sequence container (similar to vector )
18
©Fraser Hutchinson & Cliff Green Container Categories Sequence containers –vector#include –deque#include –list#include Associative containers –set, multiset#include –map, multimap#include Adapter containers –stack#include –queue, priority_queue#include
19
©Fraser Hutchinson & Cliff Green Data Structure Aspects, Sequences vector -rapid insertions/deletions at back, direct access with index list -rapid insertions/deletions anywhere, no direct access with index deque -direct access, rapid insertions at back/front stack -LIFO queue -FIFO
20
©Fraser Hutchinson & Cliff Green Data Structure Aspects, Associatives set -rapid lookup, no duplicates, stored in order multiset -same as set, duplicates OK map -1-to-1 mapping, key-based lookup, no duplicates, stored in order multimap -same as map, duplicates OK
21
©Fraser Hutchinson & Cliff Green Common Member Functions empty true if there are no members sizenumber of elements swapswaps elements of two containers begin, endforward iterator first, last element rbegin, rend reverse iterator first, last element
22
©Fraser Hutchinson & Cliff Green Common Member Functions operator=assign one container to another operator==compare two containers (if sizes same, compare each element) erase,clear erase or clear 1 or more elements
23
©Fraser Hutchinson & Cliff Green Ranges begin() refers to the first element. end() refers to the next position after the last element. [begin,end) –includes begin –excludes end –the number of elements is (end-begin) –an array of N elements is [A,A+N) –represent empty containers as [A,A)
24
©Fraser Hutchinson & Cliff Green Iterators Iterators are used to point to the elements of containers. Operators supported by iterators of all types –equality, inequality (p1=p2), (p1!=p2) –operator++ (increment) –operator* (dereference) In the implementation of STL, elements of containers are accessed only through iterators. Iterators are modeled on and share many concepts with pointers.
25
©Fraser Hutchinson & Cliff Green Input, Output, Forward Iterators Input iterators –can be used to read the elements of a container –used in algorithms: find(), accumulate(), equal() Output iterator –can be used to write the elements of a container –copy() takes an output iterator as its third argument Forward iterators –can read from or write to a container in one direction –used in algorithms: adjacent_find(), swap_range(), replace()
26
©Fraser Hutchinson & Cliff Green Bidirectional Iterators Support operator-- in addition to all the operations supported by forward iterators Used in algorithms: inplace_merge(), reverse() next_permutation()
27
©Fraser Hutchinson & Cliff Green Random Access Iterators Support all operations supported by forward and bidirectional iterators Provide access to any container element in constant time Adds remaining operators of pointer arithmetic addition and subtraction to pointer: (p+n), (p-n) subscripting: (p[n]) subtraction between iterators: (p1-p2) ordering (p1<p2) Used in algorithms: binary_search(), sort_heap() Supported by containers: vector, deque
28
©Fraser Hutchinson & Cliff Green Operations Allowed on Iterators ++p, p++all iterators *p as an rvalueinput iterators *p as an lvalueoutput iterators --p, p--reverse, bidirectional iterators p+n, p[n]random access iterators
29
©Fraser Hutchinson & Cliff Green Special Iterators Iterators used for insertion (“iterator adaptors”) –inserter –front_inserter –back_inserter Iterators used only to read elements (useful on const container declarations) –const_iterator Iterators used to traverse a list in reverse order –reverse_iterator –const_reverse_iterator
30
©Fraser Hutchinson & Cliff Green Vector Templatized ‘array’ of objects Automatically resizes if elements added (through push_back or insert methods) #include // appropriate “using” declarations vector myArray; for (int ii = 0; ii < 100; ++ii) { myArray.push_back(ii); }
31
©Fraser Hutchinson & Cliff Green Vector Details By default, vector does not perform range- checking. In the above case, the statement int val = myArray[100]; would give undefined results – if range checking desired, use at() method (throws exception if out of range)
32
©Fraser Hutchinson & Cliff Green List Lists are valuable if direct element access (through subscripting) is not needed typedef list MyStrings; // const iterator because we will not modify the list typedef list ::const_iterator Iter; MyStrings mystrings; // populate mystrings string const mymatch (“foo”); for (Iter i = mystrings.begin(); i != mystrings.end(); ++i) { if (*i == mymatch) //… do something }
33
©Fraser Hutchinson & Cliff Green List Operations Add an element to the end of the list: mystrings.push_back(my_string); Add an element to the front of the list: mystrings.push_front(my_string); Add the string before element referred to by iterator ‘i’: mystrings.insert (i, my_string); Erase the element referred to by iterator ‘i’: mystrings.erase (i);
34
©Fraser Hutchinson & Cliff Green Map When we want to access elements by a key value, we use a map. To access integer values by a string key: #include // appropriate using declarations map phonebook; void print_entry(string const & s) { cout << s << ‘ ‘ << phonebook[s] << \n” }
35
©Fraser Hutchinson & Cliff Green Map Details Subscript operator on map will create an element (default constructed), if needed –Using the insert method is frequently more appropriate Many operations use a std::pair, corresponding to the key and data values Third template parameter (typically defaulted) allows map sorting order to be changed
36
©Fraser Hutchinson & Cliff Green STL Algorithms STL algorithms are decoupled from the containers. STL algorithms may also be used with pointers and arrays. The category of iterator supported by a container determines whether the container can be used with a particular algorithm. –Mistakes are detected at compile-time.
37
©Fraser Hutchinson & Cliff Green Algorithms Sequence: a range in a container, specified by iterators start and end. –sort(iterator start, iterator end): sorts a sequence –unique_copy(iterator start, iterator end, iterator dest): makes a unique copy of a sequence –find(iterator start, iterator end, T val): searchs for val in the specified range, and returns an iterator to that element
38
©Fraser Hutchinson & Cliff Green Search Algorithms Search algorithms provide general strategies for finding if an element is in a container. Search algorithms –binary_search() –equal_range(), lower_bound(), upper_bound() –count(), count_if() –find(), find_end(), find_first_of(), find_if() –search()
39
©Fraser Hutchinson & Cliff Green Sorting and Ordering Algorithms merge() partial_sort(), partial_sort_copy() partition() random_shuffle() reverse(), reverse_copy() rotate(), rotate_copy() sort() A partition divides the container into two groups (those that satisfy a condition and those that don’t)
40
©Fraser Hutchinson & Cliff Green Deletion and Substitution Algorithms copy, copy_backwards() remove(), remove_copy(), remove_if(), remove_if_copy() replace(), replace_copy() replace_if(), replace_if_copy() swap(), swap_range(), unique()
41
©Fraser Hutchinson & Cliff Green More Algorithms Numeric algorithms –accumulate(), partial_sum() Generation and mutation algorithms –fill() –for_each() –generate() –transform()
42
©Fraser Hutchinson & Cliff Green Even More Algorithms Relational algorithms –equal() –includes() –max(), max_element() –min(), min_element() Set algorithms –set_union() –set_intersection() –set_difference()
43
©Fraser Hutchinson & Cliff Green Algorithm Constraints When not to use the generic algorithms –Cannot reorder associative containers associative containers internally maintain the order of their elements, so it is not permitted to use algorithms like sort() or partition() –Cannot use random access with a list specific list member instances of each algorithm are provided for algorithms like sort() or merge()
44
©Fraser Hutchinson & Cliff Green Functors Functors are objects that may be invoked with overloaded operator(). –Functors that return bool are called predicate functors. Many STL algorithms accept functors in their interfaces, for additional flexibilitity. Many functors are provided by STL –less, greater, equal_to –logical_and, logical_or –plus, minus, negate
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.