如果数组元素的类型为std::string,那么在不使用额外内存资源的情况下,查找数组中出现频率更高的元素的函数可以如下所示,如下面的演示程序所示。
#include <iostream>
#include <string>
size_t max_occurence( const std::string a[], size_t n )
{
size_t max = 0;
size_t max_count = 0;
for ( size_t i = 0; i != n; i++ )
{
size_t j = 0;
while ( j != i && a[j] != a[i] ) ++j;
if ( j == i )
{
size_t count = 1;
while ( ++j != n )
{
if ( a[j] == a[i] ) ++count;
}
if ( max_count < count )
{
max = i;
max_count = count;
}
}
}
return max;
}
int main()
{
std::string a[] = { "A", "B", "AA", "ABB", "B", "ABB", "B" };
auto max = max_occurence( a, sizeof( a ) / sizeof( *a ) );
std::cout << "The most often encountered string is " << a[max] << '\n';
return 0;
}
程序输出是
The most often encountered string is B
另一种方法是编写通用模板函数。例如
#include <iostream>
#include <string>
#include <functional>
#include <iterator>
template <typename ForwardIterator,
typename BinaryPredicate = std::equal_to<typename std::iterator_traits<ForwardIterator>::value_type>>
ForwardIterator max_occurence( ForwardIterator first,
ForwardIterator last,
BinaryPredicate binary_predicate = BinaryPredicate() )
{
auto max = first;
typename std::iterator_traits<ForwardIterator>::difference_type max_count = 0;
for ( auto current = first; current != last; ++current )
{
auto prev = first;
while ( prev != current && !binary_predicate( *prev, *current ) ) ++prev;
if ( prev == current )
{
typename std::iterator_traits<ForwardIterator>::difference_type count = 1;
while ( ++prev != last )
{
if ( binary_predicate( *prev, *current ) ) ++count;
}
if ( max_count < count )
{
max = current;
max_count = count;
}
}
}
return max;
}
int main()
{
std::string a[] = { "A", "B", "AA", "ABB", "B", "ABB", "B" };
auto max = max_occurence( std::begin( a ), std::end( a ) );
std::cout << "The most often encountered string is " << *max << '\n';
return 0;
}
程序输出同上图
The most often encountered string is B