This chapter is from the book
Guru Question
-
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:
-
Mechanical errors, such as invalid syntax or nonportable conventions.
-
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; }
-