To find the element with the maximum number of occurrences in a std::list in C++, you can use a std::unordered_map to count the occurrences.
In this example,
,
, and
.std::list
named data
with several integer elements.std::unordered_map
to count the occurrences of each element.#include <iostream>
#include <list>
#include <unordered_map>
int main() {
std::list<int> data = {1, 2, 2, 3, 3, 3, 4};
std::unordered_map<int, int> count;
for (int num : data) {
count[num]++;
}
int most_common = data.front();
int max_count = 0;
for (const auto& pair : count) {
if (pair.second > max_count) {
max_count = pair.second;
most_common = pair.first;
}
}
std::cout << "Element with the maximum occurrences is: " << most_common << std::endl;
return 0;
}
Element with the maximum occurrences is: 3
In this example,
,
, and
.std::list
named data
with several string elements.std::unordered_map
to count the occurrences of each element.#include <iostream>
#include <list>
#include <unordered_map>
int main() {
std::list<std::string> data = {"apple", "banana", "apple", "orange", "banana", "apple"};
std::unordered_map<std::string, int> count;
for (const auto& str : data) {
count[str]++;
}
std::string most_common = data.front();
int max_count = 0;
for (const auto& pair : count) {
if (pair.second > max_count) {
max_count = pair.second;
most_common = pair.first;
}
}
std::cout << "Element with the maximum occurrences is: " << most_common << std::endl;
return 0;
}
Element with the maximum occurrences is: apple
In this tutorial, we learned How to find the Element with Maximum Number of Occurrences in a List in C++ language with well detailed examples.