Two Lines of C++ Code to Convert an Array into Sorted Unique Elements

in #programming4 years ago

Let's say, we want to extract the unique elements (numbers) in a given array (vector, list) and return them in sorted order. For example,

The array is [1, 1, 0, 0, 2], and the output is [0, 1, 2].

You can write a method in a straightforward method with two steps - extract unique numbers and then sort them.

template <class T>
vector<T> uniqueAndSorted(const vector<T> &arr) {
    unordered_set<T> data;
    vector<T> ans;
    for (const auto &n: arr) {
        if (data.count(n)) continue;
        data.insert(n);
        ans.push_back(n);
    }
    sort(begin(ans), end(ans));
    return ans;
}

You can, implement this with the following two liner - which makes use of the set (which maintains the key in sorted order). First, we construct the set based on the given array - which will give us a set that contains unique elements. Then we just need to construct the returned vector/array and the items will be automatically in sorted order as the set maintains the keys in ascending order.

template <class T>
vector<T> uniqueAndSorted(const vector<T> &arr) {
    set<int> ans(begin(arr), end(arr));
    return vector<T>(begin(ans), end(ans));
}

--EOF (The Ultimate Computing & Technology Blog) --

Reposted to Blog of Computing


Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

Steem On!~
Every little helps! I hope this helps!


If you like my work, please consider voting for me or Buy Me a Coffee, thanks!
https://steemit.com/~witnesses type in justyy and click VOTE



Alternatively, you could proxy to me if you are too lazy to vote!

Also: you can vote me at the tool I made: https://steemyy.com/witness-voting/?witness=justyy

Coin Marketplace

STEEM 0.19
TRX 0.17
JST 0.031
BTC 81728.21
ETH 3198.83
USDT 1.00
SBD 2.82