ElsT
ElsT

Reputation: 139

get the unique number from an array, remove the duplicates completly

int a[5] = {5,2,3,2,4}

If i have an array like this, i want to get uniques
Not

5,2,3,4

but

5,3,4

Any number repeated will be removed.

I have tried using std::<set>

const size_t len = sizeof(a) / sizeof(a[0]);
std::set<int> s(a, a + len);

However, it does not work as it will produce uniques:

5,2,3,4

Upvotes: 2

Views: 67

Answers (2)

songyuanyao
songyuanyao

Reputation: 173044

You can use std::multiset with std::multiset::count, and obtain the elements only when the number of elements with the same key equals to 1 exactly. e.g.

int a[5] = {5,2,3,2,4};
const size_t len = sizeof(a) / sizeof(a[0]);  
multiset<int> m(a, a + len);

vector<int> v;

copy_if(begin(a), end(a), back_inserter(v), [&m](auto i) { return m.count(i) == 1; });

copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));

Result:

5 3 4 

LIVE

If you can't use lambda, you can write a functor instead, or write the loop directly instead of copy_if.

for (int i = 0; i < len; i++) {
    if (m.count(a[i]) == 1) 
        v.push_back(a[i]);
}

Upvotes: 3

eerorika
eerorika

Reputation: 238471

  • Sort the array. Use std::sort
  • Swap duplicate elements to end. Use std::unique
    • Now you have 2 partitions. First partition contains uniques (but includes onces that have duplicates), second contains all the duplicates. std::unique returns an iterator to the boundary of the partition (one past the last unique element).
  • Result will be uniques \ duplicates. Use std::set_difference with ranges [begin,boundary[ and [boundary, end[

Upvotes: 0

Related Questions