Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

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