fan_of_stoyan_malinin's blog

By fan_of_stoyan_malinin, history, 7 years ago, In English

Hello CF community!In tutorial I found "b"-array such as "a", but elements are distinct. Also "b" must be sorted. Nowhere is written how to build b. :(

»
7 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Add all elements of a to set and make new array with elements of that set.

set<int> s;
for (int i = 0; i < n; i++) {
    s.insert(a[i]);
}
vector<int> b;
for (set<int> :: iterator it = s.begin(); it != s.end(); it++) {
    b.pb(*it);
}

Or, simply use std::unique:

vector<int> b = a;
sort (all (b));
b.erase(b.unique(all(b)), b.end());
  • »
    »
    7 years ago, # ^ |
      Vote: I like it +9 Vote: I do not like it

    Shorter version of the first approach:

    set<int> s(a.begin(), a.end());
    vector<int> b(s.begin(), s.end());