1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include <iostream>
#include <algorithm>
using namespace std;
struct Generator {
int m_current;
Generator(int start) : m_current(start) {}
int operator()() {return m_current++;}
};
template <size_t N>
struct Comparator : public binary_function<int,int,bool> {
int (& m_a)[N];
Comparator(int (& a) [N]) : m_a(a) {}
bool operator() (const int& i, const int& j)
{
return m_a[i] < m_a[j];
}
};
template <size_t N>
inline Comparator<N> comparator(int (& a)[N])
{
return Comparator<N>(a);
}
template <size_t N>
struct Printer {
int (& m_a)[N];
Printer(int (& a) [N]) : m_a(a) {}
void operator() (const int& i)
{
cout << i << ' ' << m_a[i] << endl;
}
};
template <size_t N>
inline Printer<N> printer(int (& a)[N])
{
return Printer<N>(a);
}
#define ARRAY_SIZE(array) (sizeof((array))/sizeof((array[0])))
template <typename T, size_t N>
inline size_t array_size(T (& a)[N]) { return N; }
template <typename T, int N>
inline T* array_begin(T (& a)[N]) { return &a[0]; }
template <typename T, int N>
inline T* array_end(T (& a)[N]) { return &a[N]; }
int main()
{
int u[] = {1, 5, 4, 2, 3, 4, 4, 3, 5};
int v[ARRAY_SIZE(u)];
generate_n(&v[0], array_size(v), Generator(0));
sort(array_begin(v), array_end(v), comparator(u));
for_each(array_begin(v), array_end(v), printer(u));
int old_value = u[v[0]];
u[v[0]] = 0;
v[0] = old_value;
int unique = 0;
for (int i = 1; i < (int)array_size(v); ++i)
{
int &new_value = u[v[i]];
if (new_value != old_value)
{
++unique;
v[unique] = new_value;
old_value = new_value;
}
new_value = unique;
}
++unique;
cout << endl;
for_each(array_begin(u), array_end(u), printer(v));
cout << endl;
cout << "Uniques: " << unique;
}
| |