440 likes | 530 Views
C++ Certificate Program C++ Intermediate. Intro to the C++ Std Library. Major Components. STL subset – containers, algorithms, iterators, function objects Strings – regular and wide char Numerics – complex type, valarray Streams – iostream, stream buffer
E N D
C++ Certificate ProgramC++ Intermediate Intro to the C++ Std Library
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
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
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!
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
Std Lib Headers • All are wrapped in the standard namespace, std #include <string> // C++ string facilities #include <iostream> // iostream facilities #include <istream> // istream class #include <ostream> // ostream class #include <iomanip> // stream manipulators #include <fstream> // ifstream, ofstream facilities #include <sstream> // stringstream facilities #include <stdexcept> // exception handling classes
Std Lib Headers (cont) #include <complex> // C++ complex class #include <limits> // numeric and type limits #include <locale> // C++ locale facilities #include <memory> // allocator and auto_ptr #include <utility> // pair class, relational ops #include <bitset> // bit manipulation class #include <typeinfo> // RTTI facilities #include <new> // ‘new’ operator overloading #include <valarray> // high performance arrays (STL headers are listed later)
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
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 <iostream>#include <string>using std::cout;using std::endl; int main() { std::string const hi ("Hello world“); cout << hi << endl; return 0;}
Backwards Compatibility • Standard headers in the form <iostream> • 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’ • <stdio.h> is now <cstdio> • <string.h> is now <cstring>
Differences in C Lib Headers • The traditional C library functions are not all const-correct: • #include <string.h> // C lib string facilitieschar * strchr(const char *ptr, int c); • return value points to position in ptr, and has been replaced with • #include <cstring> // now in std namespaceconst char * strchr(const char *ptr, int c);
The String Class • <string> 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
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.
<string> Details • Std library header <string> 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
Accessing the C String in <string> • 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; }
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”);
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)
Container Categories • Sequence containers • vector #include <vector> • deque #include <deque> • list #include <list> • Associative containers • set, multiset #include <set> • map, multimap #include <map> • Adapter containers • stack #include <stack> • queue, priority_queue #include <queue>
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
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
Common Member Functions • empty true if there are no members • size number of elements • swap swaps elements of two containers • begin, end forward iterator first, last element • rbegin, rend reverse iterator first, last element
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
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)
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.
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()
Bidirectional Iterators • Support operator-- in addition to all the operations supported by forward iterators • Used in algorithms: inplace_merge(), reverse() next_permutation()
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
Operations Allowed on Iterators • ++p, p++ all iterators • *p as an rvalue input iterators • *p as an lvalue output iterators • --p, p-- reverse, bidirectional iterators • p+n, p[n] random access iterators
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
Vector • Templatized ‘array’ of objects • Automatically resizes if elements added (through push_back or insert methods) #include <vector> // appropriate “using” declarations vector<int> myArray; for (int ii = 0; ii < 100; ++ii) { myArray.push_back(ii); }
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)
List • Lists are valuable if direct element access (through subscripting) is not needed typedef list<string> MyStrings; // const iterator because we will not modify the list typedef list<string>::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 }
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);
Map • When we want to access elements by a key value, we use a map. • To access integer values by a string key: #include <map> // appropriate using declarations map<string, int> phonebook; void print_entry(string const & s) { cout << s << ‘ ‘ << phonebook[s] << \n” }
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
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.
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
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()
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)
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()
More Algorithms • Numeric algorithms • accumulate(), partial_sum() • Generation and mutation algorithms • fill() • for_each() • generate() • transform()
Even More Algorithms • Relational algorithms • equal() • includes() • max(), max_element() • min(), min_element() • Set algorithms • set_union() • set_intersection() • set_difference()
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()
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