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