2
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

1
  • use hashing . If number is present then not add it and also remove that number. Commented May 25, 2016 at 10:25

2 Answers 2

3

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

0
  • 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[

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.