I l@ve RuBoard |
![]() ![]() |
15.5 Pointers and StructuresIn 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];
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 |
![]() ![]() |