BDE 4.14.0 Production release
|
Provide a class template to extract keys as the first
attribute.
key
from value
typeThis component will, given an object of a value type consisting of a key type and some other information, return a const reference to only the key type within that object. The object passed will be of parameterized type VALUE_TYPE
, for which a type VALUE_TYPE::first_type
must be defined and be of the key type, and for which the operation .first
must be defined and must yield the object of the key type.
bslalg::HashTableImpUtil
has a static extractKey
function template that, given a value type
, will represent objects stored in a data structure, will abstract out the key type
portion of that object. In the case of the unordered_map
data structure, the value type
will be bsl::pair
, and the key type will bsl::pair::first_type
.
This section illustrates intended use of this component.
Suppose we want to define a sort
function which will work on a variety of different object types. The object has to have a key
within it, possibly the whole object, which will compare with the key
of other objects with a transitive <
operator.
First, we define our function mySort
, which takes two template args: VALUE_TYPE
, the type of object being sorted, and KEY_EXTRACTOR
, the utility class that will extra which part of the objects to be sorted is the key which will drive the sort:
Then, we define StudentRecord
, which keeps some vital statistics on students:
Next, we define two extractors for StudentRecord
, which will yield the GPA
or Age
fields:
Then, in main
, we create an array of StudentRecord
s describing a set of students, with their names, GPA's, and ages.
Next, using our GPA extractor and our mySort
function, we sort the students by GPA:
Then, we print out the sorted array of students:
The output produced is:
Note that Ann and Julie, who have the same GPA, are still in the same order as they were before the sort, as mySort
was an order-preserving sort:
Next, we sort by age with our age extractor, and print out the results:
The output is:
Note again, the ordering of students with identical ages is preserved.
Then, suppose we are storing information about employees in MyPair
objects, where first
is a double storing the employees hourly wage, and second
in the employee's name. Suppose we want to sort the employees by their hourly wages, which is the .first
field of the pair.
We declare our employee pair type:
Next, we define an array of employee pairs for employees' wages and names:
Then, we create an UnorderedMapKeyConfiguration
type parameterized on EmployeePair
, which will extract the .first
field, which is the wage, from an employee pair:
Next, we sort:
Now, we print out our results:
Finally, we see our output. Note that the ordering of Kyle and Stan, who are paid the same wage, is preserved.