- •Contents
- •Introduction
- •Who This Book Is For
- •What This Book Covers
- •How This Book Is Structured
- •What You Need to Use This Book
- •Conventions
- •Source Code
- •Errata
- •p2p.wrox.com
- •The Basics of C++
- •The Obligatory Hello, World
- •Namespaces
- •Variables
- •Operators
- •Types
- •Conditionals
- •Loops
- •Arrays
- •Functions
- •Those Are the Basics
- •Diving Deeper into C++
- •Pointers and Dynamic Memory
- •Strings in C++
- •References
- •Exceptions
- •The Many Uses of const
- •C++ as an Object-Oriented Language
- •Declaring a Class
- •Your First Useful C++ Program
- •An Employee Records System
- •The Employee Class
- •The Database Class
- •The User Interface
- •Evaluating the Program
- •What Is Programming Design?
- •The Importance of Programming Design
- •Two Rules for C++ Design
- •Abstraction
- •Reuse
- •Designing a Chess Program
- •Requirements
- •Design Steps
- •An Object-Oriented View of the World
- •Am I Thinking Procedurally?
- •The Object-Oriented Philosophy
- •Living in a World of Objects
- •Object Relationships
- •Abstraction
- •Reusing Code
- •A Note on Terminology
- •Deciding Whether or Not to Reuse Code
- •Strategies for Reusing Code
- •Bundling Third-Party Applications
- •Open-Source Libraries
- •The C++ Standard Library
- •Designing with Patterns and Techniques
- •Design Techniques
- •Design Patterns
- •The Reuse Philosophy
- •How to Design Reusable Code
- •Use Abstraction
- •Structure Your Code for Optimal Reuse
- •Design Usable Interfaces
- •Reconciling Generality and Ease of Use
- •The Need for Process
- •Software Life-Cycle Models
- •The Stagewise and Waterfall Models
- •The Spiral Method
- •The Rational Unified Process
- •Software-Engineering Methodologies
- •Extreme Programming (XP)
- •Software Triage
- •Be Open to New Ideas
- •Bring New Ideas to the Table
- •Thinking Ahead
- •Keeping It Clear
- •Elements of Good Style
- •Documenting Your Code
- •Reasons to Write Comments
- •Commenting Styles
- •Comments in This Book
- •Decomposition
- •Decomposition through Refactoring
- •Decomposition by Design
- •Decomposition in This Book
- •Naming
- •Choosing a Good Name
- •Naming Conventions
- •Using Language Features with Style
- •Use Constants
- •Take Advantage of const Variables
- •Use References Instead of Pointers
- •Use Custom Exceptions
- •Formatting
- •The Curly Brace Alignment Debate
- •Coming to Blows over Spaces and Parentheses
- •Spaces and Tabs
- •Stylistic Challenges
- •Introducing the Spreadsheet Example
- •Writing Classes
- •Class Definitions
- •Defining Methods
- •Using Objects
- •Object Life Cycles
- •Object Creation
- •Object Destruction
- •Assigning to Objects
- •Distinguishing Copying from Assignment
- •The Spreadsheet Class
- •Freeing Memory with Destructors
- •Handling Copying and Assignment
- •Different Kinds of Data Members
- •Static Data Members
- •Const Data Members
- •Reference Data Members
- •Const Reference Data Members
- •More about Methods
- •Static Methods
- •Const Methods
- •Method Overloading
- •Default Parameters
- •Inline Methods
- •Nested Classes
- •Friends
- •Operator Overloading
- •Implementing Addition
- •Overloading Arithmetic Operators
- •Overloading Comparison Operators
- •Building Types with Operator Overloading
- •Pointers to Methods and Members
- •Building Abstract Classes
- •Using Interface and Implementation Classes
- •Building Classes with Inheritance
- •Extending Classes
- •Overriding Methods
- •Inheritance for Reuse
- •The WeatherPrediction Class
- •Adding Functionality in a Subclass
- •Replacing Functionality in a Subclass
- •Respect Your Parents
- •Parent Constructors
- •Parent Destructors
- •Referring to Parent Data
- •Casting Up and Down
- •Inheritance for Polymorphism
- •Return of the Spreadsheet
- •Designing the Polymorphic Spreadsheet Cell
- •The Spreadsheet Cell Base Class
- •The Individual Subclasses
- •Leveraging Polymorphism
- •Future Considerations
- •Multiple Inheritance
- •Inheriting from Multiple Classes
- •Naming Collisions and Ambiguous Base Classes
- •Interesting and Obscure Inheritance Issues
- •Special Cases in Overriding Methods
- •Copy Constructors and the Equals Operator
- •The Truth about Virtual
- •Runtime Type Facilities
- •Non-Public Inheritance
- •Virtual Base Classes
- •Class Templates
- •Writing a Class Template
- •How the Compiler Processes Templates
- •Distributing Template Code between Files
- •Template Parameters
- •Method Templates
- •Template Class Specialization
- •Subclassing Template Classes
- •Inheritance versus Specialization
- •Function Templates
- •Function Template Specialization
- •Function Template Overloading
- •Friend Function Templates of Class Templates
- •Advanced Templates
- •More about Template Parameters
- •Template Class Partial Specialization
- •Emulating Function Partial Specialization with Overloading
- •Template Recursion
- •References
- •Reference Variables
- •Reference Data Members
- •Reference Parameters
- •Reference Return Values
- •Deciding between References and Pointers
- •Keyword Confusion
- •The const Keyword
- •The static Keyword
- •Order of Initialization of Nonlocal Variables
- •Types and Casts
- •typedefs
- •Casts
- •Scope Resolution
- •Header Files
- •C Utilities
- •Variable-Length Argument Lists
- •Preprocessor Macros
- •How to Picture Memory
- •Allocation and Deallocation
- •Arrays
- •Working with Pointers
- •Array-Pointer Duality
- •Arrays Are Pointers!
- •Not All Pointers Are Arrays!
- •Dynamic Strings
- •C-Style Strings
- •String Literals
- •The C++ string Class
- •Pointer Arithmetic
- •Custom Memory Management
- •Garbage Collection
- •Object Pools
- •Function Pointers
- •Underallocating Strings
- •Memory Leaks
- •Double-Deleting and Invalid Pointers
- •Accessing Out-of-Bounds Memory
- •Using Streams
- •What Is a Stream, Anyway?
- •Stream Sources and Destinations
- •Output with Streams
- •Input with Streams
- •Input and Output with Objects
- •String Streams
- •File Streams
- •Jumping around with seek() and tell()
- •Linking Streams Together
- •Bidirectional I/O
- •Internationalization
- •Wide Characters
- •Non-Western Character Sets
- •Locales and Facets
- •Errors and Exceptions
- •What Are Exceptions, Anyway?
- •Why Exceptions in C++ Are a Good Thing
- •Why Exceptions in C++ Are a Bad Thing
- •Our Recommendation
- •Exception Mechanics
- •Throwing and Catching Exceptions
- •Exception Types
- •Throwing and Catching Multiple Exceptions
- •Uncaught Exceptions
- •Throw Lists
- •Exceptions and Polymorphism
- •The Standard Exception Hierarchy
- •Catching Exceptions in a Class Hierarchy
- •Writing Your Own Exception Classes
- •Stack Unwinding and Cleanup
- •Catch, Cleanup, and Rethrow
- •Use Smart Pointers
- •Common Error-Handling Issues
- •Memory Allocation Errors
- •Errors in Constructors
- •Errors in Destructors
- •Putting It All Together
- •Why Overload Operators?
- •Limitations to Operator Overloading
- •Choices in Operator Overloading
- •Summary of Overloadable Operators
- •Overloading the Arithmetic Operators
- •Overloading Unary Minus and Unary Plus
- •Overloading Increment and Decrement
- •Overloading the Subscripting Operator
- •Providing Read-Only Access with operator[]
- •Non-Integral Array Indices
- •Overloading the Function Call Operator
- •Overloading the Dereferencing Operators
- •Implementing operator*
- •Implementing operator->
- •What in the World Is operator->* ?
- •Writing Conversion Operators
- •Ambiguity Problems with Conversion Operators
- •Conversions for Boolean Expressions
- •How new and delete Really Work
- •Overloading operator new and operator delete
- •Overloading operator new and operator delete with Extra Parameters
- •Two Approaches to Efficiency
- •Two Kinds of Programs
- •Is C++ an Inefficient Language?
- •Language-Level Efficiency
- •Handle Objects Efficiently
- •Use Inline Methods and Functions
- •Design-Level Efficiency
- •Cache as Much as Possible
- •Use Object Pools
- •Use Thread Pools
- •Profiling
- •Profiling Example with gprof
- •Cross-Platform Development
- •Architecture Issues
- •Implementation Issues
- •Platform-Specific Features
- •Cross-Language Development
- •Mixing C and C++
- •Shifting Paradigms
- •Linking with C Code
- •Mixing Java and C++ with JNI
- •Mixing C++ with Perl and Shell Scripts
- •Mixing C++ with Assembly Code
- •Quality Control
- •Whose Responsibility Is Testing?
- •The Life Cycle of a Bug
- •Bug-Tracking Tools
- •Unit Testing
- •Approaches to Unit Testing
- •The Unit Testing Process
- •Unit Testing in Action
- •Higher-Level Testing
- •Integration Tests
- •System Tests
- •Regression Tests
- •Tips for Successful Testing
- •The Fundamental Law of Debugging
- •Bug Taxonomies
- •Avoiding Bugs
- •Planning for Bugs
- •Error Logging
- •Debug Traces
- •Asserts
- •Debugging Techniques
- •Reproducing Bugs
- •Debugging Reproducible Bugs
- •Debugging Nonreproducible Bugs
- •Debugging Memory Problems
- •Debugging Multithreaded Programs
- •Debugging Example: Article Citations
- •Lessons from the ArticleCitations Example
- •Requirements on Elements
- •Exceptions and Error Checking
- •Iterators
- •Sequential Containers
- •Vector
- •The vector<bool> Specialization
- •deque
- •list
- •Container Adapters
- •queue
- •priority_queue
- •stack
- •Associative Containers
- •The pair Utility Class
- •multimap
- •multiset
- •Other Containers
- •Arrays as STL Containers
- •Strings as STL Containers
- •Streams as STL Containers
- •bitset
- •The find() and find_if() Algorithms
- •The accumulate() Algorithms
- •Function Objects
- •Arithmetic Function Objects
- •Comparison Function Objects
- •Logical Function Objects
- •Function Object Adapters
- •Writing Your Own Function Objects
- •Algorithm Details
- •Utility Algorithms
- •Nonmodifying Algorithms
- •Modifying Algorithms
- •Sorting Algorithms
- •Set Algorithms
- •The Voter Registration Audit Problem Statement
- •The auditVoterRolls() Function
- •The getDuplicates() Function
- •The RemoveNames Functor
- •The NameInList Functor
- •Testing the auditVoterRolls() Function
- •Allocators
- •Iterator Adapters
- •Reverse Iterators
- •Stream Iterators
- •Insert Iterators
- •Extending the STL
- •Why Extend the STL?
- •Writing an STL Algorithm
- •Writing an STL Container
- •The Appeal of Distributed Computing
- •Distribution for Scalability
- •Distribution for Reliability
- •Distribution for Centrality
- •Distributed Content
- •Distributed versus Networked
- •Distributed Objects
- •Serialization and Marshalling
- •Remote Procedure Calls
- •CORBA
- •Interface Definition Language
- •Implementing the Class
- •Using the Objects
- •A Crash Course in XML
- •XML as a Distributed Object Technology
- •Generating and Parsing XML in C++
- •XML Validation
- •Building a Distributed Object with XML
- •SOAP (Simple Object Access Protocol)
- •. . . Write a Class
- •. . . Subclass an Existing Class
- •. . . Throw and Catch Exceptions
- •. . . Read from a File
- •. . . Write to a File
- •. . . Write a Template Class
- •There Must Be a Better Way
- •Smart Pointers with Reference Counting
- •Double Dispatch
- •Mix-In Classes
- •Object-Oriented Frameworks
- •Working with Frameworks
- •The Model-View-Controller Paradigm
- •The Singleton Pattern
- •Example: A Logging Mechanism
- •Implementation of a Singleton
- •Using a Singleton
- •Example: A Car Factory Simulation
- •Implementation of a Factory
- •Using a Factory
- •Other Uses of Factories
- •The Proxy Pattern
- •Example: Hiding Network Connectivity Issues
- •Implementation of a Proxy
- •Using a Proxy
- •The Adapter Pattern
- •Example: Adapting an XML Library
- •Implementation of an Adapter
- •Using an Adapter
- •The Decorator Pattern
- •Example: Defining Styles in Web Pages
- •Implementation of a Decorator
- •Using a Decorator
- •The Chain of Responsibility Pattern
- •Example: Event Handling
- •Implementation of a Chain of Responsibility
- •Using a Chain of Responsibility
- •Example: Event Handling
- •Implementation of an Observer
- •Using an Observer
- •Chapter 1: A Crash Course in C++
- •Chapter 3: Designing with Objects
- •Chapter 4: Designing with Libraries and Patterns
- •Chapter 5: Designing for Reuse
- •Chapter 7: Coding with Style
- •Chapters 8 and 9: Classes and Objects
- •Chapter 11: Writing Generic Code with Templates
- •Chapter 14: Demystifying C++ I/O
- •Chapter 15: Handling Errors
- •Chapter 16: Overloading C++ Operators
- •Chapter 17: Writing Efficient C++
- •Chapter 19: Becoming Adept at Testing
- •Chapter 20: Conquering Debugging
- •Chapter 24: Exploring Distributed Objects
- •Chapter 26: Applying Design Patterns
- •Beginning C++
- •General C++
- •I/O Streams
- •The C++ Standard Library
- •C++ Templates
- •Integrating C++ and Other Languages
- •Algorithms and Data Structures
- •Open-Source Software
- •Software-Engineering Methodology
- •Programming Style
- •Computer Architecture
- •Efficiency
- •Testing
- •Debugging
- •Distributed Objects
- •CORBA
- •XML and SOAP
- •Design Patterns
- •Index
Delving into the STL: Containers and Iterators
simultaneously. Note that it’s possible for elements that are objects to be equal to each other with operator== even if they are not identical. We don’t show an example of the multiset because it’s so similar to set and multimap.
Other Containers
As mentioned earlier, there are several other parts of the C++ language that work with the STL to varying degrees, including arrays, strings, streams, and the bitset.
Arrays as STL Containers
Recall that “dumb” pointers are bona fide iterators because they support the required operators. This point is more than just a piece of trivia. It means that you can treat normal C++ arrays as STL containers by using pointers to their elements as iterators. Arrays, of course, don’t provide methods like size(), empty(), insert(), and erase(), so they aren’t true STL containers. Nevertheless, because they do support iterators through pointers, you can use them in the algorithms described in Chapter 22 and in some of the methods described in this chapter.
For example, you could copy all the elements of an array into a vector using the vector insert() method that takes an iterator range from any container. The insert() method prototype looks like this:
template <typename InputIterator> void insert(iterator position,
InputIterator first, InputIterator last);
If you want to use an int array as the source, then the templatized type of InputIterator becomes int*. Here is the full example:
#include <vector> #include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int arr[10]; // normal C++ array vector<int> vec; // STL vector
//
//Initialize each element of the array to the value of
//its index.
//
for (int i = 0; i < 10; i++) { arr[i] = i;
}
//
//Insert the contents of the array into the
//end of the vector.
//
vec.insert(vec.end(), arr, arr + 10);
611
Chapter 21
// Print the contents of the vector. for (i = 0; i < 10; i++) {
cout << vec[i] << “ “;
}
return (0);
}
Note that the iterator referring to the first element of the array is simply the address of the first element. Recall from Chapter 13 that the name of an array alone is interpreted as the address of the first element. The iterator referring to the end must be one past the last element, so it’s the address of the first element plus 10.
Strings as STL Containers
You can think of a string as a sequential container of characters. Thus, it shouldn’t be surprising to learn that the C++ string is a full-fledged sequential container. It contains begin() and end() methods that return iterators into the string, insert() and erase() methods, size(), empty(), and all the rest of the sequential container basics. It resembles a vector quite closely, even providing methods reserve() and capacity(). However, unlike vectors, strings are not required to store their elements contiguously in memory. They also fail to provide a few methods that vectors support, such as push_back().
The C++ string is actually a typedef of a char instantiation of the basic_string template class. However, we refer to string for simplicity. The discussion here applies equally to wstring and other instantiations of the basic_string template.
You can use string as an STL container just as you would use vector. Here is an example:
#include <string> #include <iostream> using namespace std;
int main(int argc, char** argv)
{
string str1;
str1.insert(str1.end(), ‘h’); str1.insert(str1.end(), ‘e’); str1.insert(str1.end(), ‘l’); str1.insert(str1.end(), ‘l’); str1.insert(str1.end(), ‘o’);
for (string::const_iterator it = str1.begin(); it != str1.end(); ++it) { cout << *it;
}
cout << endl;
return (0);
}
612
Delving into the STL: Containers and Iterators
In addition to the STL sequential container methods, strings provide a whole host of useful methods and friend functions. The string interface is actually quite a good example of a cluttered interface, one of the design pitfalls discussed in Chapter 5. The full string interface is summarized in the Standard Library Reference resource on the Web site; this section merely showed you how strings can be used as STL containers.
Streams as STL Containers
Input and output streams are not containers in the traditional sense: they do not store elements. However, they can be considered sequences of elements, and as such share some characteristics with the STL containers. C++ streams do not provide any STL-related methods directly, but the STL supplies special iterators called istream_iterator and ostream_iterator that allow you to “iterate” through input and output streams. Chapter 23 explains how to use them.
bitset
The bitset is a fixed-length abstraction of a sequence of bits. Recall that a bit can represent two values, often referred to as 1 and 0, on and off, or true and false. The bitset also uses the terminology set and unset. You can toggle or flip a bit from one value to the other.
The bitset is not a true STL container: it’s of fixed size, it’s not templatized on an element type, and it doesn’t support iteration. However, it’s a useful utility, which is often lumped with the containers, so we provide a brief introduction here. The Standard Library Reference resource on the Web site contains a thorough summary of the bitset operations.
bitset Basics
The bitset, defined in the <bitset> header file, is templatized on the number of bits it stores. The default constructor initializes all fields of the bitset to 0. An alternative constructor creates the bitset from a string of 0s and 1s.
You can adjust the values of the individual bits with the set(), reset(), and flip() methods, and you can access and set individual fields with an overloaded operator[]. Note that operator[] on a non-const object returns a proxy object to which you can assign a Boolean value, call flip(), or negate with ~. You can also access individual fields with the test() method.
Additionally, you can stream bitsets with the normal insertion and extraction operators. The bitset is streamed as a string of 0s and 1s.
Here is a small example:
#include <bitset> #include <iostream> using namespace std;
int main(int argc, char** argv)
{
bitset<10> myBitset;
myBitset.set(3);
myBitset.set(6);
613
Chapter 21
myBitset[8] = true; myBitset[9] = myBitset[3];
if (myBitset.test(3)) {
cout << “Bit 3 is set!\n”;
}
cout << myBitset << endl;
return (0);
}
The output is:
Bit 3 is set! 1101001000
Note that the leftmost character in the output string is the highest numbered bit.
Bitwise Operators
In addition to basic bit manipulation routines, the bitset provides implementations of all the bitwise operators: &, |, ^, ~, <<, >>, &=, |=, ^=, <<=, and >>=. They behave just as they would on a “real” sequence of bits. Here is an example:
#include <bitset> #include <iostream> using namespace std;
int main(int argc, char** argv)
{
string str1 = “0011001100”; string str2 = “0000111100”;
bitset<10> bitsOne(str1), bitsTwo(str2);
bitset<10> bitsThree = bitsOne & bitsTwo; cout << bitsThree << endl;
bitsThree <<= 4;
cout << bitsThree << endl;
return (0);
}
The output of the program is:
0000001100
0011000000
bitset Example: Representing Cable Channels
One possible use of bitsets is tracking channels of cable subscribers. Each subscriber could have a bitset of channels associated with his or her subscription, with set bits representing the channels to which he or she actually subscribes. This system could also support “packages” of channels, also represented as bitsets, which represent commonly subscribed combinations of channels.
614
Delving into the STL: Containers and Iterators
The following CableCompany class is a simple example of this model. It uses two maps, each of string/ bitset, storing the cable packages as well as the subscriber information.
#include <bitset> #include <map> #include <string> #include <stdexcept> using std::map; using std::bitset; using std::string;
using std::out_of_range;
const int kNumChannels = 10;
class CableCompany
{
public: CableCompany() {}
// Adds the package with the specified channels to the databse void addPackage(const string& packageName,
const bitset<kNumChannels>& channels);
//Removes the specified package from the database void removePackage(const string& packageName);
//Adds the customer to the database with initial channels found in package
//Throws out_of_range if the package name is invalid.
void newCustomer(const string& name, const string& package) throw (out_of_range);
//Adds the customer to the database with initial channels specified
//in channels
void newCustomer(const string& name, const bitset<kNumChannels>& channels);
//Adds the channel to the customers profile void addChannel(const string& name, int channel);
//Removes the channel from the customers profile void removeChannel(const string& name, int channel);
//Adds the specified package to the customers profile
void addPackageToCustomer(const string& name, const string& package);
//Removes the specified customer from the database void deleteCustomer(const string& name);
//Retrieves the channels to which this customer subscribes
//Throws out_of_range if name is not a valid customer bitset<kNumChannels>& getCustomerChannels(const string& name)
throw (out_of_range);
protected:
typedef map<string, bitset<kNumChannels> > MapType; MapType mPackages, mCustomers;
};
615
Chapter 21
Here are the implementations of the preceding methods:
#include “CableCompany.h” using namespace std;
void CableCompany::addPackage(const string& packageName, const bitset<kNumChannels>& channels)
{
// Just make a key/value pair and insert it into the packages map. mPackages.insert(make_pair(packageName, channels));
}
void CableCompany::removePackage(const string& packageName)
{
// Just erase the package from the package map. mPackages.erase(packageName);
}
void CableCompany::newCustomer(const string& name, const string& package) throw (out_of_range)
{
// Get a reference to the specified package. MapType::const_iterator it = mPackages.find(package); if (it == mPackages.end()) {
//That package doesn’t exist. Throw an exception. throw (out_of_range(“Invalid package”));
}else {
//Create the account with the bitset representing that package.
//Note that it refers to a name/bitset pair. The bitset is the
//second field.
mCustomers.insert(make_pair(name, it->second));
}
}
void CableCompany::newCustomer(const string& name, const bitset<kNumChannels>& channels)
{
// Just add the customer/channels pair to the customers map. mCustomers.insert(make_pair(name, channels));
}
void CableCompany::addChannel(const string& name, int channel)
{
// Find a reference to the customers. MapType::iterator it = mCustomers.find(name); if (it != mCustomers.end()) {
//We found this customer; set the channel.
//Note that it is a reference to a name/bitset pair.
//The bitset is the second field.
it->second.set(channel);
}
}
void CableCompany::removeChannel(const string& name, int channel)
{
616
Delving into the STL: Containers and Iterators
// Find a reference to the customers. MapType::iterator it = mCustomers.find(name); if (it != mCustomers.end()) {
//We found this customer; remove the channel.
//Note that it is a refernce to a name/bitset pair.
//The bitset is the second field.
it->second.reset(channel);
}
}
void CableCompany::addPackageToCustomer(const string& name, const string& package)
{
// Find the package.
MapType::iterator itPack = mPackages.find(package); // Find the customer.
MapType::iterator itCust = mCustomers.find(name);
if (itCust != mCustomers.end() && itPack != mPackages.end()) {
//Only if both package and customer are found, can we do the update.
//Or-in the package to the customers existing channels.
//Note that it is a reference to a name/bitset pair.
//The bitset is the second field.
itCust->second |= itPack->second;
}
}
void CableCompany::deleteCustomer(const string& name)
{
// Remove the customer with this name. mCustomers.erase(name);
}
bitset<kNumChannels>& CableCompany::getCustomerChannels(const string& name) throw (out_of_range)
{
// Find the customer.
MapType::iterator it = mCustomers.find(name); if (it != mCustomers.end()) {
//Found it!
//Note that it is a reference to a name/bitset pair.
//The bitset is the second field.
return (it->second);
}
// Didn’t find it. Throw an exception.
throw (out_of_range(“No customer of that name”));
}
Finally, here is a simple program demonstrating how to use the CableCompany class:
#include “CableCompany.h” #include <iostream> using namespace std;
int main(int argc, char** argv)
{
CableCompany myCC;
617
Chapter 21
string basic_pkg = “1111000000”; string premium_pkg = “1111111111”; string sports_pkg = “0000100111”;
myCC.addPackage(“basic”, bitset<kNumChannels>(basic_pkg)); myCC.addPackage(“premium”, bitset<kNumChannels>(premium_pkg)); myCC.addPackage(“sports”, bitset<kNumChannels>(sports_pkg));
myCC.newCustomer(“Nicholas Solter”, “basic”); myCC.addPackageToCustomer(“Nicholas Solter”, “sports”); cout << myCC.getCustomerChannels(“Nicholas Solter”) << endl;
return (0);
}
Summar y
This chapter introduced the standard template library containers. It also presented sample code illustrating a variety of uses to which you can put these containers. Hopefully you appreciate the power of the vector, deque, list, stack, queue, priority_queue, map, multimap, set, multiset, string, and bitset. Even if you don’t incorporate them into your programs immediately, at least keep them in the back of your mind for future projects.
Now that you are familiar with the containers, the next chapter can illustrate the true beauty of the STL by discussing the generic algorithms. Chapter 23, the third, and final, STL chapter, closes with a discussion of the more advanced features and provides a sample container and iterator implementation.
618
Mastering STL Algorithms
and Function Objects
As you read in Chapter 21, the STL provides an impressive collection of generic data structures. Most libraries stop there. The STL, however, contains an additional assortment of generic algorithms that can, with some exceptions, be applied to elements from any container. Using these algorithms, you can find elements in containers, sort elements in containers, process elements in containers, and perform a whole host of other operations. The beauty of the algorithms is that they are independent not only of the types of the underlying elements, but of the types of the containers on which they operate. Algorithms perform their work using only the iterator interfaces.
Many of the algorithms accept callbacks: a function pointer or something that behaves like a function pointer, such as an object with an overloaded operator(). Conveniently, the STL provides a set of classes that can be used to create callback objects for the algorithms. These callback objects are called function objects, or just functors.
This chapter includes:
An overview of the algorithms and three sample algorithms: find(), find_if(), and accumulate()
A detailed look at function objects
Predefined function object classes: arithmetic function objects, comparison function objects, and logical function objects
Function object adapters
How to write your own function objects