I l@ve RuBoard Previous Section Next Section

15.5 Pointers and Structures

In Chapter 12, you defined a structure for a mailing list:

struct mailing { 
    std::string   name;    // Last name, first name 
    std::string   address1;// Two lines of street address 
    std::string   address2; 
    std::string   city;      
    char     state[2];     // Two-character abbreviation[2]
    long int zip;          // Numeric zip code
} list[MAX_ENTRIES]; 

[2] Every once in a while, someone will send in a bug report stating that the size of the character array should be 3: two for the state abbreviation and one for the end of string character. In this example, the state is a character array, not a C-style string. We know that it contains two and only two characters, so we can represent it as two-character array.

Mailing lists must frequently be sorted in name order and Zip-code order. You could sort the entries themselves, but each entry is 226 bytes long. That's a lot of data to move around. A way around this problem is to declare an array of pointers and then sort the pointers:

// Pointer to the data
struct mailing *list_ptrs[MAX_ENTRIES];  

int current;    // Current mailing list entry

    // ....

    for (current = 0; current = number_of_entries; ++current) {
        list_ptrs = &list[current]; 
       ++list_ptrs;
    }

    // Sort list_ptrs by zip code

Now instead of having to move a large structure around, you are moving 4-byte pointers. This sorting is much faster. Imagine that you had a warehouse full of big heavy boxes and you needed to locate any box quickly. One way of doing this would be to put the boxes in alphabetical order. But that would require a lot of moving, so you assign each location a number, write down the name and number on index cards, and sort the cards by name.

    I l@ve RuBoard Previous Section Next Section