Skip to content

Commit 9928541

Browse files
committed
Merge branch 'master' of github.com:fredbr/algorithm-implementations
2 parents f0a9f9c + 82f3a35 commit 9928541

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

etc/compression.cpp

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,33 @@
33
using 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

2021
int va[] = {0, 1000, 2000, 5000, 3000};
2122
vector<int> v{1000, 2000, 5000, 3000};
2223

2324
int 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

Comments
 (0)