I have a string array like
{"A", "B", "AA", "ABB", "B", "ABB", "B"}
how do I find the string ( "B" ) which occurs the largest number of times in an array like this in c++?
Thank you
I have a string array like
{"A", "B", "AA", "ABB", "B", "ABB", "B"}
how do I find the string ( "B" ) which occurs the largest number of times in an array like this in c++?
Thank you
On
Here's an example using std::map.
typedef std::map<std::string, int> Frequency_Map;
int main()
{
const std::vector<std::string> test_data =
{
"A", "B", "AA", "ABB", "B", "ABB", "B",
};
Frequency_Map frequency_table;
std::string s;
const size_t length = test_data.length();
for (unsigned int i = 0; i < length; ++i)
{
Frequency_Map::iterator iter(frequency_table.find(test_data[i]);
if (iter != frequency_table.end())
{
++(iter->second);
}
else
{
frequency_table[test_data[i]] = 1;
}
}
for (Frequency_Map::iterator iter = frequency_table.begin();
iter != frequency_table.end();
++iter)
{
std::cout << iter->first << " " << iter->second << "\n";
}
return 0;
}
The code above builds a frequency table using std::map and then outputs the strings and their frequencies. The above code can easily be modified to find the string that has the largest (maximum) frequency.
If elements of the array has the type
std::stringthen without using additional memory resources the function that finds the element that occurs more often in an array can look the following way as it is shown in the demonstrative program below.The program output is
An alternative approach is to write a generic template function. For example
The program output is the same as shown above