C++ 使用句柄

来源:互联网 发布:七上生物行知天下答案 编辑:程序博客网 时间:2024/06/02 01:18

15.8.3.Using the Handle

Comparing TwoSales_items

theassociative containers allow us to specify a function (or function object(Section 14.8, p. 530)) to use as the comparison function. We do so similarlyto the way we passed a separate function to the stable_sortalgorithm in Section11.2.3(p. 403). In that case, we needed only to pass an additional argument tostable_sortto provide a comparison function to use in place of the<operator. Overriding an associative container's comparison function is abit more complicated because, as we shall see, we must supply the comparisonfunction when we define the container object.

Let'sstart with the easy part, which is to define a function to use to compareSales_item objects:

 

// compare definesitem ordering for the multiset in Basket

inline bool

compare(constSales_item &lhs, const Sales_item &rhs)

{

return lhs->book()< rhs->book();

}

 

Ourcomparefunction has the same interface as the less-than operator. It returns abooland takes two constreferences to Sales_items. It compares the parameters bycomparing their ISBNs. This function uses the Sales_item ->operator, whichreturns a pointer to an Item_base object. That pointer is used to fetch and runthe bookmember, which returns the ISBN.

 

Using a Comparatorwith an Associative Container

So,to use our Sales_itemcomparison function, we must specify the comparator typewhen we define the multiset. In our case, that type is a function that returnsa booland takes two const Sales_itemreferences.

We'llstart by defining a typedef that is a synonym for this type (Section 7.9, p.276):

 

// type of thecomparison function used to order the multiset

typedef bool(*Comp)(const Sales_item&, const Sales_item&);

 

Thisstatement defines Compas a synonym for the pointer to function type thatmatches the comparison function we wish to use to compare Sales_itemobjects. Nextwe'll need to define a multisetthat holds objects of type Sales_itemand thatuses this Comptype for its comparison function. Each constructor for the associativecontainers allows us to supply the name of the comparison function. We candefine an empty multiset that uses our comparefunction as follows:

std::multiset<Sales_item,Comp> items(compare);

 

Thisdefinition says that itemsis a multisetthat holds Sales_itemobjects and uses anobject of type Comp to compare them. The multisetis emptywe supplied noelementsbut we did supply a comparison function named compare. When we add orlook for elements in itemsour compare function will be used to order themultiset.

 

Containersand Handle Classes

Nowthat we know how to supply a comparison function, we'll define a class, namedBasket, to keep track of a sale and calculate the purchase price:

 

class Basket {

// type of thecomparison function used to order the multiset

typedef bool(*Comp)(const Sales_item&, const Sales_item&);

public:

// make it easier totype the type of our set

typedefstd::multiset<Sales_item, Comp> set_type;

// typedefs modeledafter corresponding container types

typedefset_type::size_type size_type;

typedefset_type::const_iterator const_iter;

Basket():items(compare) { } // initialze the comparator

void add_item(constSales_item &item)

{ items.insert(item);}

size_type size(constSales_item &i) const

{ returnitems.count(i); }

double total() const; //sum of net prices for all items in the basket

private:

std::multiset<Sales_item,Comp> items;

};

 

Using the Handle toExecute a Virtual Function

Usingthe Handle to Execute a Virtual Function

Theonly complicated member of class Basketis the totalfunction, which returns theprice for all the items in the basket:

 

double Basket::total()const

{

double sum = 0.0; //holds the running total

/* find each set ofitems with the same  isbn and calculate

* the net price forthat quantity of items

* iter refers to firstcopy of each book in the set

* upper_bound refersto next element with a different isbn

*/

for (const_iter iter =items.begin();

iter != items.end();iter =

items.upper_bound(*iter))

{

// we know there's atleast one element with this key in the Basket

// virtual call tonet_price applies appropriate discounts, if any

sum +=(*iter)->net_price(items.count(*iter));

}

return sum;

}

 

 

0 0
原创粉丝点击