Solved

# Frequency algorithm for STL containers

Posted on 2006-11-21
334 Views
Is there an STL algorithm to find the element which occurs the most often in a container?
Thanks.
0
Question by:Rothbard
• 2

LVL 53

Assisted Solution

Infinity08 earned 150 total points
No, not to my knowledge.

You could use a multiset though, in combination with the count method :

size_type count(const key_type& k) const

That will give you the number of elements with a certain value (key). If you repeat that for all values, you can easily extract the max.

That's the first though that comes to mind for your requirements ...
0

LVL 53

Assisted Solution

Infinity08 earned 150 total points
fyi, here's a nice list of the STL algorithms :

http://www.josuttis.com/libbook/algolist.pdf
0

LVL 39

Accepted Solution

itsmeandnobodyelse earned 350 total points
It is not very difficult to write your own template function, e. g. like the function below.

Regards, Alex

#include <vector>
#include <iostream>
#include <algorithm>

template<class I, class T>
int occurs_mostoften(I i1, I i2, T& t)
{
std::vector<T> v(i1, i2);
std::sort(v.begin(), v.end());
int c = 0; int idx = -1; int mc =  0;
std::vector<T>::iterator il = v.begin();
std::vector<T>::iterator im = v.begin();
for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it)
{
if (!(*il < *it) && !(*it < *il) )
{
if (++c > mc)
{
mc = c;
im = il;
}
}
else
{
c = 1;
il = it;
}
}

if (im != v.end()) t = *im;
return mc;
}

int main()
{
int a[] = { 4, 6, 3, 4, 2, 8, 3, 2, 3, 1, 0, 4, 1, 3, 2, 9, 7, 3 };
vector<int> v(&a[0], &a[sizeof(a)/sizeof(int)]);
vector<int>::iterator it;
int c, r = -1;
if ((c = occurs_mostoften(v.begin(), v.end(), r)) > 0)
{
std::cout << r << " : " << c << endl;
}
return 0;
}

0

Author Comment

Thanks to all who replied!
0

## Featured Post

### Suggested Solutions

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.