cs11 – introduction to c++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf ·...
TRANSCRIPT
![Page 1: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/1.jpg)
CS11 – Introduction to C++
Winter 2011-2012 Lecture 8
![Page 2: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/2.jpg)
Local Variables
string getUsername() { string user; cout << "Enter username: " << endl; cin >> user; return user; }
n What happens to user when function returns? q It gets cleaned up automatically when the function returns
![Page 3: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/3.jpg)
Returning References
string & getUsername() { string user; cout << "Enter username: " << endl; cin >> user; return user; }
n Now, what does getUsername() return? q A reference to the local variable user q Big mistake – user goes away, then reference becomes invalid!
n Never return references (or pointers) to local variables! n In general, be very careful when returning references.
q The referenced object must outlive the caller’s use of it
![Page 4: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/4.jpg)
References and Arithmetic Operators
n From Lab 4B: // Implement + for sparse-vectors. const SparseVector & SparseVector::operator+( const SparseVector &rhs) const { return SparseVector(*this) += rhs; }
n Does this work? q This also returns a reference to a local variable. q More subtle, since the variable is an unnamed temporary q Will eventually result in a catastrophic failure of some kind
n Simple arithmetic operators should always return a const-object value (e.g. const SparseVector)
![Page 5: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/5.jpg)
Multiple Header Files
n Lab 6 has 13 classes in two header files: q Expression etc. - expressions.hh q Command etc. - commands.hh
n Managing relationships between header files can be annoying! q Commands depend on expressions q Other files depend on both of these q Easily leads to “multiple declaration” errors
![Page 6: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/6.jpg)
Header Files and Multiple Inclusion
n Can’t declare something multiple times! q Classes, functions, variables, … q Generates compiler errors.
n Solution is to use include-guards q Use the C++ preprocessor to make sure that each
include file’s contents are only included once. q Uses the preprocessor directives:
n #ifndef – if not defined … n #define – define some symbol … n #endif – end of #ifdef, #ifndef, or #if
preprocessor block
![Page 7: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/7.jpg)
The Preprocessor
n Preprocessor directives start with # character n Performs simple text-level processing before the
actual compilation phase begins q Inclusion of named files
n #include "expressions.hh"
q Macro substitution n #define MAX_SPEED 65 n Our old friend assert(...) is also a macro
q Conditional compilation n Can optionally include or exclude chunks of code n Great for writing applications that run on multiple platforms
![Page 8: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/8.jpg)
Include-Guards
n Enclose contents of include file with a guard #ifndef SOMEFILE_HH #define SOMEFILE_HH ... // Normal header file contents #endif // SOMEFILE_HH
q Comment after #endif is just for readability n First time file is included, symbol isn’t defined.
q Symbol will be defined on subsequent inclusions, so contents won’t be repeated.
n Choose a symbol name that is likely not to be used elsewhere! q Some variant of header file’s name is usually safe
![Page 9: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/9.jpg)
Other Header File Notes
n Results of preprocessing sometimes saved into temporary files q Not so often anymore, but common in the past! q If you are writing macros, may need to look at
preprocessor output to debug your work q Most compilers provide a switch for that
n g++ -save-temps ...
n Including lots of header files can dramatically increase compile times q Only include header files that you need.
![Page 10: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/10.jpg)
Inside the assert() Macro
n C/C++ assert() macro uses the preprocessor #ifdef NDEBUG #define assert(e) ((void) 0) #else #define assert(e) \ ((void) ((e) ? 0 : __assert(#e, __FILE__, __LINE__))) ... // Definition of __assert() #endif
n If NDEBUG symbol is defined during compilation, assert() becomes a no-op q g++ -DNDEBUG ... q -D… defines the specified symbol when compiling
![Page 11: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/11.jpg)
Inside the assert() Macro (2)
n C/C++ assert() macro: #ifdef NDEBUG #define assert(e) ((void) 0) #else #define assert(e) \ ((void) ((e) ? 0 : __assert(#e, __FILE__, __LINE__))) ... // Definition of __assert() #endif
n __FILE__ and __LINE__ are special symbols q Managed/updated by the preprocessor q __FILE__ is file currently being compiled (.cc or .hh) q __LINE__ is the current line of file being compiled
![Page 12: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/12.jpg)
Inside the assert() Macro (3)
n C/C++ assert() macro: #ifdef NDEBUG #define assert(e) ((void) 0) #else #define assert(e) \ ((void) ((e) ? 0 : __assert(#e, __FILE__, __LINE__))) ... // Definition of __assert() #endif
n assert() returns no value: ((void) ...) n expr ? true_val : false_val
q A ternary (3-arg) operator, an “inline if-statement” q If expr is true, use true_val; otherwise use false_val
![Page 13: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/13.jpg)
Inside the assert() Macro (4)
n C/C++ assert() macro: #ifdef NDEBUG #define assert(e) ((void) 0) #else #define assert(e) \ ((void) ((e) ? 0 : __assert(#e, __FILE__, __LINE__))) ... // Definition of __assert() #endif
n Finally, the definition contains no semicolons! n Provided by the caller: assert(curr->value != 0);
![Page 14: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/14.jpg)
The C++ Standard Template Library
n Lab 7 is a brief introduction to the capabilities of the Standard Template Library (“the STL”)
n Generate a search index for a text document q Make a list of unique words q Keep a count of each word’s occurrences q Find out if a word appears in a set of stop-words
n The STL is a very powerful set of tools for managing and processing information q Definitely want to learn this library!
![Page 15: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/15.jpg)
What Is the STL?
n A set of generic containers, algorithms, and iterators that provide many of the basic algorithms and data structures of computer science.
n Generic q Heavily parameterized; lots of templates
n Containers q Collections of other objects, with various characteristics.
n Algorithms q For manipulating the data stored in containers.
n Iterators q “A generalization of pointers.” q Cleanly decouple algorithms from containers.
![Page 16: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/16.jpg)
Some STL Containers
n First category of containers: Sequences q Use indexing for access q Keep their values in a specific order
n vector – a growable array q Constant indexing, linear cost for insert/resize
n deque – double-ended queue q Constant prepend/append time, linear insert time
n list – a doubly linked list q Constant insert time, linear cost for indexing q Supports forward and backward traversal
n slist – a singly linked list q Only supports forward traversal
![Page 17: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/17.jpg)
More STL Containers
n The other category: Associative Containers q Use keys for access – unique values, any type q Tend to keep values in a specific order, but not required to!
n set, multiset – ordered collection of keys q In set, keys are unique; in multiset, can appear multiple times q log(n) time for insert, lookup
n map, multimap – ordered collection of (key, value) pairs q In map, keys are unique; in multimap, can appear multiple times q log(n) time for insert, lookup q Entries are ordered by key
n hash_set, hash_multiset – unordered collection of keys q Like set, multiset, but with constant insert/lookup time
n hash_map, hash_multimap – unordered (key, value) pairs q Like map, multimap, but with constant insert/lookup time
![Page 18: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/18.jpg)
STL Customization
n STL containers are templates q Can apply them in your programs very easily q Can customize them in many ways
n Parameters specify the container element types
n vector<float> numbers; q A vector (growable array) of floating-point values q Individual values can appear multiple times
n set<string> wordSet; q Each word appears only once in the set q Words are kept in alphabetical order
![Page 19: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/19.jpg)
STL Customization (2)
n set<string, greater<string> > wordSet; q Second parameter specifies how to order the elements in
the set! q Default value is std::less<T> function-template, uses <
for comparison q Can reverse the order the values are kept by specifying std::greater<T>, which uses > for comparison
![Page 20: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/20.jpg)
Example: Tracking Word-Counts
n Want to generate a search-index from a text document
n What does program need to keep track of? q A mapping from each word we’ve seen, to the
number of times that word appears n Can use the STL map template: #include <map> map<string, int> wordCounts; q First argument is the key type – a given word q Second argument is the value type – the number
of times that word appears
![Page 21: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/21.jpg)
Example: Tracking Word-Counts (2)
n STL maps support array-indexing syntax: wordCounts["foo"]++; q Increments the count for the word “foo” q If “foo” hasn’t been stored in map before, initial
value is automatically 0 cout << wordCounts["bar"] << endl; q Outputs the current count for the word “bar” q If haven’t set wordCounts["bar"] before, this
will evaluate to 0.
![Page 22: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/22.jpg)
C++ Strings
n C++ inherits C notion of char* as a “string” q Zero-terminated array of char values q Useful C functions for string manipulation in <cstring>
header (C++ name for string.h) n C++ introduces the string class
q Dynamically allocated, resizable string q Provides many features and benefits over char* strings q Generally painless to use in very complex ways q Prefer string to char*, wherever possible! q #include <string>
![Page 23: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/23.jpg)
Basic C++ String Operations
n C++ string objects can be initialized from other strings, or from char* values
string s1 = "green"; // Same as s1("green"); string s2 = s1; // Same as s2(s1);
q s2 is an independent copy of s1 n string supports assignment from string or char*
s2 = s1; s1 = "gray";
n string supports comparison operators q == != < > etc. q Lexicographic comparison operations q Case sensitive by default
![Page 24: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/24.jpg)
String Lengths and Indexes
n length() member-function reports number of characters in string string color = "chartreuse"; cout << color << " has " << color.length() << " characters." << endl;
q (string also has a size() member-function) n Characters have indexes 0 to length() - 1
![Page 25: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/25.jpg)
Individual Characters
n Individual characters can be accessed or mutated with []
string word = "far"; cout << word[2] << endl; word[1] = 'o'; // now word == "for"
![Page 26: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/26.jpg)
Classifying Characters
n Useful helper functions in <cctype> header q (from the C standard header ctype.h) int isalpha(int) Any letter: a..z or A..Z in C locale int isupper(int) Uppercase letter: A..Z in C locale int islower(int) Lowercase letter: a..z in C locale int isdigit(int) Decimal digit: 0..9 int isxdigit(int) Hexadecimal digit: 0..9, a..f or A..F int isspace(int) Any whitespace character etc. q Note that these functions take an int and return an int! q They actually take a character value, and return true
(nonzero) / false (zero) based on the character’s category
![Page 27: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/27.jpg)
Classifying Characters (2)
n Also in <cctype> header: int toupper(int) Convert letter to uppercase int tolower(int) Convert letter to lowercase q Again, the functions are declared to take an int and return
an int q They actually take a character value, and return another
character value that is the uppercase (or lowercase) version of the input
![Page 28: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/28.jpg)
String Manipulation
n substr() extracts a substring substr(size_type start, size_type length)
q Returns a new string containing the substring q start is an index in range 0 to length() - 1
n Example: string s1 = "computer"; string s2 = s1.substr(3, 3); q s2 is “put”
![Page 29: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/29.jpg)
STL Algorithms
n Another nifty feature of STL: Algorithms q Standard processing operations on collections q for_each, find, count, copy, … q swap, transform, replace, reverse, rotate, random_shuffle, …
q sort, stable_sort, merge, set_union, set_intersection, set_difference, min_element, max_element, …
n All customizable in a number of ways.
![Page 30: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/30.jpg)
Using STL
n Just like C++, STL has many subtleties and gotchas q Simple tasks using STL are usually fine q More sophisticated use can be very problematic
n Read good books on the topic: q Effective STL by Scott Meyers
![Page 31: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/31.jpg)
C++ Track Review
n We have covered: q Declaring and defining classes q C++ object-references and const correctness q Operator overloads for user-defined types q Dynamic memory management in C++ q Writing generic template classes q Introduction to exception handling q Class hierarchies, inheritance, virtual functions
n Primarily focused on C++ Core Language
![Page 32: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec8.pdf · Lab 7 is a brief introduction to the capabilities of the Standard Template Library](https://reader033.vdocument.in/reader033/viewer/2022053007/5f0abced7e708231d42d193e/html5/thumbnails/32.jpg)
Advanced C++ Track
n Focuses primarily on C++ Standard Library q Standard classes and features implemented on
top of C++ Core Language q Strings, streams, standard exceptions q Standard Template Library
n Focuses even more on how to use C++ well q Managing allocated memory with smart pointers q Using exceptions safely and effectively q Build tools to facilitate larger projects q Other neat tools, libraries, C++ language topics!