Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to find the element with minimum occurrences in a vector with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <optional>
 
// Generic function that works with vectors of any printable/hashable type
template <typename T>
std::optional<T> min_occurrence(const std::vector<T>& vec) {
    if (vec.empty()) {
        return std::nullopt; // Handle empty vector safely
    }
 
    std::unordered_map<T, size_t> counts;
    for (const auto& item : vec) {
        counts[item]++;
    }
 
    auto min_it = std::min_element(
        counts.begin(), counts.end(),
        [](const auto& a, const auto& b) {
            return a.second < b.second;
        }
    );
 
    return min_it->first;
}
 
int main() {
    std::vector<int> vec = {1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3};
 
    auto result = min_occurrence(vec);
    if (result.has_value()) {
        std::cout << result.value() << std::endl; // Output: 5
    }
}
 
 
 
/*
run:
 
5
 
*/

 



answered Sep 25 by avibootz
edited Sep 25 by avibootz
...