Style Case Studies: Index Tables
(Page 1 of 6 )
This book evaluates style versus structure in C++ programming, emphasizing using the C++ standard library effectively. This item on index tables focuses on how to implement them not just effectively but exceptionally. (This book excerpt is from
Exceptional C++ Style by Herb Sutter, ISBN 0201760428, copyright 2005. All rights reserved. It is reprinted with permission from Addison-Wesley Professional.)
Editor's Note: This book presents puzzles or problems. A question is posed by JG, a term for new junior-grade military officer, and an answer from a Guru.
Item 34. Index Tables
Index tables are a genuinely useful idiom and a technique that’s worth being aware of. But how can we implement the technique effectively… nay, even better than that, exceptionally?
JG Question
1. Who benefits from clear, understandable code?
Guru Question
2. The following code presents an interesting and genuinely useful idiom for creating index tables into existing containers. For a more detailed explanation, see the original article [Hicks00].
Critique this code and identify:
a) Mechanical errors, such as invalid syntax or nonportable conventions.
b) Stylistic improvements that would improve code clarity, reusability, and maintainability.
// program sort_idxtbl(…) to make a permuted array of indices
#include <vector>
#include <algorith>
template <class RAIter>
struct sort_idxtbl_pair
{
RAIter it;
int i;
bool operator<( const sort_idxtbl_pair& s )
{ return (*it) < (*(s.it)); }
void set( const RAIter& _it, int _i ) { it=_it; i=_i; }
sort_idxtbl_pair() {}
};
template <class RAIter>
void sort_idxtbl( RAIter first, RAIter last, int* pidxtbl )
{
int iDst = last-first;
typedef std::vector< sort_idxtbl_pair<RAIter> > V;
V v( iDst );
int i=0;
RAIter it = first;
V::iterator vit = v.begin();
for( i=0; it<last; it++, vit++, i++ )
(*vit).set(it,i);
std::sort(v.begin(), v.end());
int *pi = pidxtbl;
vit = v.begin();
for( ; vit<v.end(); pi++, vit++ )
*pi = (*vit).i;
}
main()
{
int ai[10] = { 15,12,13,14,18,11,10,17,16,19 };
cout << “#################” << endl;
std::vector<int> vecai(ai, ai+10);
int aidxtbl[10];
sort_idxtbl(vecai.begin(), vecai.end(), aidxtbl);
for (int i=0; i<10; i++)
cout << “i=“ << i
<< “, aidxtbl[i]=“ << aidxtbl[i]
<< “, ai[aidxtbl[i]]=“ << ai[aidxtbl[i]]
<< endl;
cout << “#################” << endl;
}
This chapter is from Exceptional C++ Style, by Herb Sutter (ISBN 0201760428, copyright 2005. All rights reserved. It is reprinted with permission from Addison-Wesley Professional). Check it out at your favorite bookstore today.
Buy this book now. |
Next: Solution to Item 34: Dissecting Index Tables >>
More Code Examples Articles
More By Addison-Wesley/Prentice Hall PTR