- •Thinking in C++ 2nd edition Volume 2: Standard Libraries & Advanced Topics
- •Preface
- •What’s new in the second edition
- •What’s in Volume 2 of this book
- •How to get Volume 2
- •Prerequisites
- •Learning C++
- •Goals
- •Chapters
- •Exercises
- •Exercise solutions
- •Source code
- •Language standards
- •Language support
- •The book’s CD ROM
- •Seminars, CD Roms & consulting
- •Errors
- •Acknowledgements
- •Library overview
- •1: Strings
- •What’s in a string
- •Creating and initializing C++ strings
- •Initialization limitations
- •Operating on strings
- •Appending, inserting and concatenating strings
- •Replacing string characters
- •Concatenation using non-member overloaded operators
- •Searching in strings
- •Finding in reverse
- •Finding first/last of a set
- •Removing characters from strings
- •Stripping HTML tags
- •Comparing strings
- •Using iterators
- •Iterating in reverse
- •Strings and character traits
- •A string application
- •Summary
- •Exercises
- •2: Iostreams
- •Why iostreams?
- •True wrapping
- •Iostreams to the rescue
- •Sneak preview of operator overloading
- •Inserters and extractors
- •Manipulators
- •Common usage
- •Line-oriented input
- •Overloaded versions of get( )
- •Reading raw bytes
- •Error handling
- •File iostreams
- •Open modes
- •Iostream buffering
- •Seeking in iostreams
- •Creating read/write files
- •User-allocated storage
- •Output strstreams
- •Automatic storage allocation
- •Proving movement
- •A better way
- •Output stream formatting
- •Internal formatting data
- •Format fields
- •Width, fill and precision
- •An exhaustive example
- •Formatting manipulators
- •Manipulators with arguments
- •Creating manipulators
- •Effectors
- •Iostream examples
- •Code generation
- •Maintaining class library source
- •Detecting compiler errors
- •A simple datalogger
- •Generating test data
- •Verifying & viewing the data
- •Counting editor
- •Breaking up big files
- •Summary
- •Exercises
- •3: Templates in depth
- •Nontype template arguments
- •Typedefing a typename
- •Using typename instead of class
- •Function templates
- •A string conversion system
- •A memory allocation system
- •Type induction in function templates
- •Taking the address of a generated function template
- •Local classes in templates
- •Applying a function to an STL sequence
- •Template-templates
- •Member function templates
- •Why virtual member template functions are disallowed
- •Nested template classes
- •Template specializations
- •A practical example
- •Pointer specialization
- •Partial ordering of function templates
- •Design & efficiency
- •Preventing template bloat
- •Explicit instantiation
- •Explicit specification of template functions
- •Controlling template instantiation
- •Template programming idioms
- •Summary
- •Containers and iterators
- •STL reference documentation
- •The Standard Template Library
- •The basic concepts
- •Containers of strings
- •Inheriting from STL containers
- •A plethora of iterators
- •Iterators in reversible containers
- •Iterator categories
- •Input: read-only, one pass
- •Output: write-only, one pass
- •Forward: multiple read/write
- •Bidirectional: operator--
- •Random-access: like a pointer
- •Is this really important?
- •Predefined iterators
- •IO stream iterators
- •Manipulating raw storage
- •Basic sequences: vector, list & deque
- •Basic sequence operations
- •vector
- •Cost of overflowing allocated storage
- •Inserting and erasing elements
- •deque
- •Converting between sequences
- •Cost of overflowing allocated storage
- •Checked random-access
- •list
- •Special list operations
- •list vs. set
- •Swapping all basic sequences
- •Robustness of lists
- •Performance comparison
- •A completely reusable tokenizer
- •stack
- •queue
- •Priority queues
- •Holding bits
- •bitset<n>
- •vector<bool>
- •Associative containers
- •Generators and fillers for associative containers
- •The magic of maps
- •A command-line argument tool
- •Multimaps and duplicate keys
- •Multisets
- •Combining STL containers
- •Creating your own containers
- •Summary
- •Exercises
- •5: STL Algorithms
- •Function objects
- •Classification of function objects
- •Automatic creation of function objects
- •Binders
- •Function pointer adapters
- •SGI extensions
- •A catalog of STL algorithms
- •Support tools for example creation
- •Filling & generating
- •Example
- •Counting
- •Example
- •Manipulating sequences
- •Example
- •Searching & replacing
- •Example
- •Comparing ranges
- •Example
- •Removing elements
- •Example
- •Sorting and operations on sorted ranges
- •Sorting
- •Example
- •Locating elements in sorted ranges
- •Example
- •Merging sorted ranges
- •Example
- •Set operations on sorted ranges
- •Example
- •Heap operations
- •Applying an operation to each element in a range
- •Examples
- •Numeric algorithms
- •Example
- •General utilities
- •Creating your own STL-style algorithms
- •Summary
- •Exercises
- •Perspective
- •Duplicate subobjects
- •Ambiguous upcasting
- •virtual base classes
- •The "most derived" class and virtual base initialization
- •"Tying off" virtual bases with a default constructor
- •Overhead
- •Upcasting
- •Persistence
- •MI-based persistence
- •Improved persistence
- •Avoiding MI
- •Mixin types
- •Repairing an interface
- •Summary
- •Exercises
- •7: Exception handling
- •Error handling in C
- •Throwing an exception
- •Catching an exception
- •The try block
- •Exception handlers
- •Termination vs. resumption
- •The exception specification
- •Better exception specifications?
- •Catching any exception
- •Rethrowing an exception
- •Uncaught exceptions
- •Function-level try blocks
- •Cleaning up
- •Constructors
- •Making everything an object
- •Exception matching
- •Standard exceptions
- •Programming with exceptions
- •When to avoid exceptions
- •Not for asynchronous events
- •Not for ordinary error conditions
- •Not for flow-of-control
- •You’re not forced to use exceptions
- •New exceptions, old code
- •Typical uses of exceptions
- •Always use exception specifications
- •Start with standard exceptions
- •Nest your own exceptions
- •Use exception hierarchies
- •Multiple inheritance
- •Catch by reference, not by value
- •Throw exceptions in constructors
- •Don’t cause exceptions in destructors
- •Avoid naked pointers
- •Overhead
- •Summary
- •Exercises
- •8: Run-time type identification
- •The “Shape” example
- •What is RTTI?
- •Two syntaxes for RTTI
- •Syntax specifics
- •Producing the proper type name
- •Nonpolymorphic types
- •Casting to intermediate levels
- •void pointers
- •Using RTTI with templates
- •References
- •Exceptions
- •Multiple inheritance
- •Sensible uses for RTTI
- •Revisiting the trash recycler
- •Mechanism & overhead of RTTI
- •Creating your own RTTI
- •Explicit cast syntax
- •Summary
- •Exercises
- •9: Building stable systems
- •Shared objects & reference counting
- •Reference-counted class hierarchies
- •Finding memory leaks
- •An extended canonical form
- •Exercises
- •10: Design patterns
- •The pattern concept
- •The singleton
- •Variations on singleton
- •Classifying patterns
- •Features, idioms, patterns
- •Basic complexity hiding
- •Factories: encapsulating object creation
- •Polymorphic factories
- •Abstract factories
- •Virtual constructors
- •Destructor operation
- •Callbacks
- •Observer
- •The “interface” idiom
- •The “inner class” idiom
- •The observer example
- •Multiple dispatching
- •Visitor, a type of multiple dispatching
- •Efficiency
- •Flyweight
- •The composite
- •Evolving a design: the trash recycler
- •Improving the design
- •“Make more objects”
- •A pattern for prototyping creation
- •Trash subclasses
- •Parsing Trash from an external file
- •Recycling with prototyping
- •Abstracting usage
- •Applying double dispatching
- •Implementing the double dispatch
- •Applying the visitor pattern
- •More coupling?
- •RTTI considered harmful?
- •Summary
- •Exercises
- •11: Tools & topics
- •The code extractor
- •Debugging
- •Trace macros
- •Trace file
- •Abstract base class for debugging
- •Tracking new/delete & malloc/free
- •CGI programming in C++
- •Encoding data for CGI
- •The CGI parser
- •Testing the CGI parser
- •Using POST
- •Handling mailing lists
- •Maintaining your list
- •Mailing to your list
- •A general information-extraction CGI program
- •Parsing the data files
- •Summary
- •Exercises
- •General C++
- •My own list of books
- •Depth & dark corners
- •Design Patterns
- •Index
operator+ and operator+= are a very flexible and convenient means of combining string data. On the right hand side of the statement, you can use almost any type that evaluates to a group of one or more characters.
Searching in strings
The find family of string member functions allows you to locate a character or group of characters within a given string. Here are the members of the find family and their general usage:
string find member function |
What/how it finds |
|
|
find( ) |
Searches a string for a specified character or |
|
group of characters and returns the starting |
|
position of the first occurrence found or npos |
|
if no match is found. (npos is a const of –1 |
|
and indicates that a search failed.) |
|
|
find_first_of( ) |
Searches a target string and returns the |
|
position of the first match of any character in |
|
a specified group. If no match is found, it |
|
returns npos. |
|
|
find_last_of( ) |
Searches a target string and returns the |
|
position of the last match of any character in |
|
a specified group. If no match is found, it |
|
returns npos. |
|
|
find_first_not_of( ) |
Searches a target string and returns the |
|
position of the first element that doesn’t |
|
match any character in a specified group. If |
|
no such element is found, it returns npos. |
|
|
find_last_not_of( ) |
Searches a target string and returns the |
|
position of the element with the largest |
|
subscript that doesn’t match of any character |
|
in a specified group. If no such element is |
|
found, it returns npos. |
|
|
rfind( ) |
Searches a string from end to beginning for a |
|
specified character or group of characters and |
|
returns the starting position of the match if |
|
one is found. If no match is found, it returns |
|
npos. |
|
|
String searching member functions and their general uses
Chapter 14: Templates & Container Classes
38
The simplest use of find( ) searches for one or more characters in a string. This overloaded version of find( ) takes a parameter that specifies the character(s) for which to search, and optionally one that tells it where in the string to begin searching for the occurrence of a substring. (The default position at which to begin searching is 0.) By setting the call to find inside a loop, you can easily move through a string, repeating a search in order to find all of the occurrences of a given character or group of characters within the string.
Notice that we define the string object sieveChars using a constructor idiom which sets the initial size of the character array and writes the value ‘P’ to each of its member.
//: C01:Sieve.cpp #include <string> #include <iostream> using namespace std;
int main() {
//Create a 50 char string and set each
//element to 'P' for Prime
string sieveChars(50, 'P');
//By definition neither 0 nor 1 is prime.
//Change these elements to "N" for Not Prime sieveChars.replace(0, 2, "NN");
//Walk through the array:
for(int i = 2;
i <= (sieveChars.size() / 2) - 1; i++) // Find all the factors:
for(int factor = 2;
factor * i < sieveChars.size();factor++) sieveChars[factor * i] = 'N';
cout << "Prime:" << endl;
//Return the index of the first 'P' element: int j = sieveChars.find('P');
//While not at the end of the string: while(j != sieveChars.npos) {
//If the element is P, the index is a prime cout << j << " ";
//Move past the last prime
j++;
// Find the next prime
j = sieveChars.find('P', j);
}
cout << "\n Not prime:" << endl;
// Find the first element value not equal P:
Chapter 14: Templates & Container Classes
39
|
|
j |
= |
sieveChars.find_first_not_of('P'); |
||||||||||||
|
|
while(j != sieveChars.npos) { |
|
|
|
|||||||||||
|
|
|
cout << j << " "; |
|
|
|
|
|
|
|||||||
|
|
|
j++; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
j |
= sieveChars.find_first_not_of('P', j); |
||||||||||||
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
} ///:~ |
|
|
|
|
|
|
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
||||||||||
The output from Sieve.cpp looks like this: |
|
|
|
|
|
|||||||||||
|
Prime: |
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||
|
2 |
3 |
5 |
7 |
11 |
13 |
17 |
19 |
23 |
29 |
31 |
37 |
41 |
43 |
47 |
|
|
Not |
prime: |
|
|
|
|
|
|
|
|
|
|
||||
|
0 |
1 |
4 |
6 |
8 |
9 |
10 |
12 |
14 |
15 |
16 |
18 |
20 |
21 |
22 |
|
|
24 |
|
25 |
26 |
|
27 |
28 |
30 |
32 |
33 |
34 |
35 |
36 |
38 |
39 |
|
|
40 |
|
42 |
44 |
|
45 |
46 |
48 |
49 |
|
|
|
|
|
|
|
find( ) allows you to walk forward through a string, detecting multiple occurrences of a character or group of characters, while find_first_not_of( ) allows you to test for the absence of a character or group.
The find member is also useful for detecting the occurrence of a sequence of characters in a string:
//: C01:Find.cpp
// Find a group of characters in a string #include <string>
#include <iostream> using namespace std;
int main() {
string chooseOne("Eenie, meenie, miney, mo"); int i = chooseOne.find("een");
while(i != string::npos) { cout << i << endl;
i++;
i = chooseOne.find("een", i);
}
} ///:~
Find.cpp produces a single line of output :
8
This tells us that the first ‘e’ of the search group “een” was found in the word “meenie,” and is the eighth element in the string. Notice that find passed over the “Een” group of characters in the word “Eenie”. The find member function performs a case sensitive search.
Chapter 14: Templates & Container Classes
40
There are no functions in the string class to change the case of a string, but these functions can be easily created using the Standard C library functions toupper( ) and tolower( ), which change the case of one character at a time. A few small changes will make Find.cpp perform a case insensitive search:
//: C01:NewFind.cpp #include <string> #include <iostream> using namespace std;
//Make an uppercase copy of s: string upperCase(string& s) {
char* buf = new char[s.length()]; s.copy(buf, s.length());
for(int i = 0; i < s.length(); i++) buf[i] = toupper(buf[i]);
string r(buf, s.length()); delete buf;
return r;
}
//Make a lowercase copy of s:
string lowerCase(string& s) {
char* buf = new char[s.length()]; s.copy(buf, s.length());
for(int i = 0; i < s.length(); i++) buf[i] = tolower(buf[i]);
string r(buf, s.length()); delete buf;
return r;
}
int main() {
string chooseOne("Eenie, meenie, miney, mo"); cout << chooseOne << endl;
cout << upperCase(chooseOne) << endl; cout << lowerCase(chooseOne) << endl; // Case sensitive search
int i = chooseOne.find("een"); while(i != string::npos) {
cout << i << endl; i++;
i = chooseOne.find("een", i);
}
Chapter 14: Templates & Container Classes
41
// Search lowercase:
string lcase = lowerCase(chooseOne); cout << lcase << endl;
i = lcase.find("een"); while(i != lcase.npos) {
cout << i << endl; i++;
i = lcase.find("een", i);
}
// Search uppercase:
string ucase = upperCase(chooseOne); cout << ucase << endl;
i = ucase.find("EEN"); while(i != ucase.npos) {
cout << i << endl; i++;
i = ucase.find("EEN", i);
}
} ///:~
Both the upperCase( ) and lowerCase( ) functions follow the same form: they allocate storage to hold the data in the argument string, copy the data and change the case. Then they create a new string with the new data, release the buffer and return the result string. The c_str( ) function cannot be used to produce a pointer to directly manipulate the data in the string because c_str( ) returns a pointer to const. That is, you’re not allowed to manipulate string data with a pointer, only with member functions. If you need to use the more primitive char array manipulation, you should use the technique shown above.
The output looks like this:
Eenie, meenie, miney, mo EENIE, MEENIE, MINEY, MO eenie, meenie, miney, mo 8
eenie, meenie, miney, mo 0 8
EENIE, MEENIE, MINEY, MO 0 8
The case insensitive searches found both occurrences on the “een” group.
NewFind.cpp isn’t the best solution to the case sensitivity problem, so we’ll revisit it when we examine string comparisons.
Chapter 14: Templates & Container Classes
42