mark occurances of elements in array cpp
#include <iostream>
#include <unordered_map>
#include <vector>
void markOccurrences(const std::vector<int>& arr) {
std::unordered_map<int, int> occurrences;
// Count occurrences of each element in the array
for (int num : arr) {
occurrences[num]++;
}
// Print the elements along with their occurrences
for (size_t i = 0; i < arr.size(); ++i) {
if (occurrences[arr[i]] != -1) {
std::cout << arr[i] << " occurs " << occurrences[arr[i]] << " times." << std::endl;
occurrences[arr[i]] = -1; // Mark the element as visited
}
}
}
int main() {
std::vector<int> array = {1, 2, 3, 2, 1, 3, 4, 5, 4, 6, 7, 8, 8};
std::cout << "Occurrences in the array:" << std::endl;
markOccurrences(array);
return 0;
}
This C++ code snippet defines a function markOccurrences
that takes in a vector of integers (arr
). It uses an unordered_map
to count the occurrences of each element in the input array. The function then iterates through the array and prints each unique element along with its count of occurrences.
In the main
function, an example array of integers is created, and markOccurrences
is called on this array to demonstrate the functionality.