> בתאריך יום שלישי, 2 בפברואר 2010 בשעה 15:11:41 UTC+5:30, מאת dushkin:
>> Hi all.
>>
>> Is it possible to know (without iterating ofcourse) how many unique
>> keys are in a multiset?
>> I know that a set has unique values, but I would prefer using
>> multiset in my solution if I have the unique keys counting solution.
>>
>> Example:
>>
>> Given a multiset with values: {1,1,2,4,5,4,3,1} - The unique counting
>> will give me 5 for {1,2,3,4,5} keys.
You need to iterate as this information is not maintained by
std::multiset. However, the iteration can be hidden in a std algorithm,
e.g.:
int CalcUniq(const std::multiset<int>& x) {
if (x.empty()) {
return 0;
} else {
int prev = *x.begin();
return std::accumulate(std::next(x.begin()), x.end(), 1,
[&prev](int sum, int k) {
int diff = (k != prev); prev = k; return sum + diff; });
}
}
Another option is to make a wrapper class around multiset which keeps
account of the number of unique elements.