Docsity

CS11 - Introduction to C++: Local Variables, References, Header Files, and the STL, Exams of Computer science

Partial preview of the text

Download CS11 - Introduction to C++: Local Variables, References, Header Files, and the STL and more Exams Computer science in PDF only on Docsity!

CS11 – Introduction to C++

Winter 2011-

Lecture 8

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

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)

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

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

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

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

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

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);

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!

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

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

STL Customization (2)

n set<string, greater > wordSet; q Second parameter specifies how to order the elements in the set! q Default value is std::less function-template, uses < for comparison q Can reverse the order the values are kept by specifying std::greater, which uses > for comparison

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<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