33using namespace std ;
44
55
6- // compresses positions [0,n) to values [1 , n]
7- template <typename T >
8- void compress (T&& v, int n )
6+ // compresses positions [0,n) to values [pos , n+pos ]
7+ template <typename Iter >
8+ void compress (Iter ini, Iter fim, int pos= 1 )
99{
10- vector<typename decay<decltype (v[0 ])>::type> vv (n);
11- for (int i = 0 ; i < n; i++)
12- vv[i] = v[i];
10+ using T = typename decay<decltype (*ini)>::type;
1311
12+ vector<T> vv (fim-ini);
13+ copy (ini, fim, vv.begin ());
1414 sort (vv.begin (), vv.end ());
15-
16- for (int i = 0 ; i < n; i++)
17- v[i] = lower_bound (vv.begin (), vv.end (), v[i]) - vv.begin () + 1 ;
15+ vv.erase (unique (vv.begin (), vv.end ()), vv.end ());
16+ for_each (ini, fim, [&] (T& x) {
17+ x = lower_bound (vv.begin (), vv.end (), x)-vv.begin () + pos;
18+ });
1819}
1920
2021int va[] = {0 , 1000 , 2000 , 5000 , 3000 };
2122vector<int > v{1000 , 2000 , 5000 , 3000 };
2223
2324int main ()
2425{
25- compress (va+1 , 4 );
26- compress (v, 4 );
26+ compress (va+1 , va+ 5 , 1 );
27+ compress (v. begin (), v. end (), 0 );
2728
2829 for (int i = 1 ; i <= 4 ; i++)
2930 cout << va[i] << " " ;
3031 cout << " \n " ;
3132
3233 for (int i : v) cout << i << " " ;
3334 cout << " \n " ;
34- }
35+ }
0 commit comments