Files Classes Functions Hierarchy
00001 #include <cassert> 00002 #include <iostream> 00003 #include <vector> 00004 #include <cmath> 00005 #include <algorithm> 00006 using namespace std; 00007 00008 #include <indextable.h> 00009 #include <indextabletest.h> 00010 #include <print.h> 00011 #include <typedefs.h> 00012 00013 00014 00015 // 00016 // About: The ideas came from a public code review by 00017 // Herb Sutter http://www.gotw.ca/gotw/073.htm#1 00018 // 00019 00020 00021 // Client comparision function. {3k,3k+1,3k+2} 00022 class partition3 00023 { 00024 public: 00025 00026 bool operator()(int a, int b) 00027 { return ((a%3) < (b%3)); } 00028 }; 00029 00030 // This code is from http://www.gotw.ca/gotw/073.htm 00031 // and was a proposed solution in the code review. 00032 // I have formatted it so that it is better to read. 00033 namespace Solution2 00034 { 00035 00036 template< class T, class U > 00037 struct ComparPair1stDeref 00038 { 00039 bool operator() 00040 ( 00041 pair<T,U> const & a, 00042 pair<T,U> const & b 00043 ) const 00044 { return *a.first<*b.first; } 00045 }; 00046 00047 template< class IterIn, class IterOut > 00048 void sortIndexTable 00049 ( 00050 IterIn first, 00051 IterIn last, 00052 IterOut out 00053 ) 00054 { 00055 vector<pair<IterIn,int> > s(last-first); 00056 for (uint i=0; i<s.size(); ++i) 00057 s[i]=make_pair(first+i,i); 00058 sort 00059 ( 00060 s.begin(), 00061 s.end(), 00062 ComparPair1stDeref<IterIn,int>() 00063 ); 00064 for (uint i=0; i<s.size(); ++i,++out) 00065 *out=s[i].second; 00066 } 00067 00068 } 00069 00070 00071 void indextabletest01() 00072 { 00073 uintc aimax=10; 00074 int ai[10]={15,12,13,14,18,11,10,17,16,19}; 00075 vector<int> aidxtbl(aimax); 00076 Solution2::sortIndexTable(ai,ai+aimax,aidxtbl.begin()); 00077 00078 cout << "######################" << endl; 00079 for (uint i=0; i<aimax; ++i) 00080 cout << SHOW(i) 00081 << "," << SHOW(aidxtbl[i]) 00082 << "," << SHOW(ai[aidxtbl[i]]) 00083 << endl; 00084 00085 cout << "######################" << endl; 00086 00087 sortIndexTable(aidxtbl.begin(),partition3(),ai,ai+aimax); 00088 for (uint i=0; i<aimax; ++i) 00089 cout << SHOW(i) 00090 << "," << SHOW(aidxtbl[i]) 00091 << "," << SHOW(ai[aidxtbl[i]]) 00092 << endl; 00093 00094 cout << "######################" << endl; 00095 00096 sortIndexTable(aidxtbl.begin(),less<int>(),ai,ai+aimax); 00097 for (uint i=0; i<aimax; ++i) 00098 cout << SHOW(i) 00099 << "," << SHOW(aidxtbl[i]) 00100 << "," << SHOW(ai[aidxtbl[i]]) 00101 << endl; 00102 00103 cout << "######################" << endl; 00104 00105 vector<uint> aidxtbl2; 00106 vector<int> ai2(ai,ai+aimax); 00107 sortIndexTable(aidxtbl2,greater<int>(),ai2); 00108 for (uint i=0; i<aimax; ++i) 00109 cout << SHOW(i) 00110 << "," << SHOW(aidxtbl2[i]) 00111 << "," << SHOW(ai[aidxtbl2[i]]) 00112 << endl; 00113 00114 } 00115 00116 00117 00118
1.5.8