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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

How to group elements of a vector based on their first occurrence in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <unordered_map>

// Function to group elements by their first occurrence
std::vector<int> groupElements(const std::vector<int>& vec) {
    std::unordered_map<int, int> frequencyMap; // To store the frequency of each element
    std::vector<int> result;                   // To store the grouped elements
    std::vector<int> order;                    // To maintain the order of first occurrences

    // Count frequencies and track the order of first occurrences
    for (int num : vec) {
        if (frequencyMap.find(num) == frequencyMap.end()) {
            order.push_back(num); // Add to order if it's the first occurrence
        }
        frequencyMap[num]++;
    }

    // Group elements based on their first occurrence
    for (int num : order) {
        for (int i = 0; i < frequencyMap[num]; i++) {
            result.push_back(num);
        }
    }

    return result;
}

int main() {
    std::vector<int> vec = {88, 33, 77, 88, 22, 55, 88, 55, 11, 99, 88, 11, 77};

    // Group elements
    std::vector<int> groupedVector = groupElements(vec);

    // Output the grouped vector
    std::cout << "Grouped vector: ";
    for (int num : groupedVector) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}

  
  
/*
run:
  
Grouped vector: 88 88 88 88 33 77 77 22 55 55 11 11 99 
  
*/

 



answered Oct 10, 2025 by avibootz
...