Reputation: 139
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
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
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
Reputation: 238471
std::sort
std::unique
std::unique
returns an iterator to the boundary of the partition (one past the last unique element).uniques \ duplicates
. Use std::set_difference
with ranges [begin,boundary[
and [boundary, end[
Upvotes: 0