S
Steve555
Hi,
Given a vector, I'm trying to find the most frequently occurring
element, and return it, along with a count of its frequency.
Although I've got a way of doing it below, this gets called millions
of times in an inner loop and I need to speed it up if possible.
I'm looping through each element of the vector, and using std::count
to count it's frequency:
long FindMostFrequentInVector(vector<long> *inVec, long *maxElement)
{
long c, maxFreq=0, e;
for(long i=0; i<inVec->size(); i++)
{
e = (*inVec);
c = count(inVec->begin(), inVec->end(), e);
if(c > maxFreq)
{
* maxElement = e;
maxFreq = c;
}
}
return maxFreq;
}
I can inline it, but for now I'd prefer to keep it in it's own
function; it's the logic I'm more interested in.
For my application, if it makes a difference, there are known
constraints:
1) inVec->size() will _never_ be greater than 10,
2) the elements' values will _always_ be between 0 and 200.
3) it doesn't matter that there may be 2 or more elements with equally
maximum frequency, any one will do.
(in the above example, the last one found will be the one returned.)
On a separate note, when passing arrays or vectors in to a function,
am I right in assuming it's faster to pass a pointer and deference it
with (*inVec) each time?
Thanks
Steve
Given a vector, I'm trying to find the most frequently occurring
element, and return it, along with a count of its frequency.
Although I've got a way of doing it below, this gets called millions
of times in an inner loop and I need to speed it up if possible.
I'm looping through each element of the vector, and using std::count
to count it's frequency:
long FindMostFrequentInVector(vector<long> *inVec, long *maxElement)
{
long c, maxFreq=0, e;
for(long i=0; i<inVec->size(); i++)
{
e = (*inVec);
c = count(inVec->begin(), inVec->end(), e);
if(c > maxFreq)
{
* maxElement = e;
maxFreq = c;
}
}
return maxFreq;
}
I can inline it, but for now I'd prefer to keep it in it's own
function; it's the logic I'm more interested in.
For my application, if it makes a difference, there are known
constraints:
1) inVec->size() will _never_ be greater than 10,
2) the elements' values will _always_ be between 0 and 200.
3) it doesn't matter that there may be 2 or more elements with equally
maximum frequency, any one will do.
(in the above example, the last one found will be the one returned.)
On a separate note, when passing arrays or vectors in to a function,
am I right in assuming it's faster to pass a pointer and deference it
with (*inVec) each time?
Thanks
Steve