Home > OS >  Iterate through vector<uchar> and count occurrence of values
Iterate through vector<uchar> and count occurrence of values

Time:05-08

How to iterate through a std::vector<uchar> and count the occurrence of each value?

I'm still fairly new to C and don't really know the best approaches

My guess would be to iterate through the vector and register each occurrence in a new multidimensional vector

std::vector<uchar<int>> unique;
for(const auto& sample : quantized){
    // if unique[sample] does not exists create it and set the value to 1
    // if unique[sample] is set increase it by  1
}

And how would the logic look like in the above code? (if this is the best approach?)

I need to find the value with most occurrencies

CodePudding user response:

We use an unordered_map as a counter by key.

#include <cstdio>
#include <unordered_map>
#include <vector>
#include <algorithm>

int main(int argc, char const *argv[]) {

  // counter, key is sample, value is count
  std::unordered_map<int, int> counter;
  auto samples = std::vector<int>{1, 2, 3, 4, 5, 6, 7,  8, 9, 10,
                                  4, 5, 6, 7, 8, 9, 10, 8, 9, 10};
  // count samples
  for (auto sample : samples) {
    counter[sample]  ;
  }
  // sort
  std::vector<int> desc_keys;
  desc_keys.reserve(counter.size());
  for (auto const &kv : counter) {
    desc_keys.push_back(kv.first);
  }
  // -- desc
    std::sort(desc_keys.begin(), desc_keys.end(),
                [](int a, int b) { return a > b; });
  // print
  for (auto key : desc_keys) {
    printf("%d: %d\n", key, counter[key]);
  }
  return 0;
}

output:

10: 3
9: 3
8: 3
7: 2
6: 2
5: 2
4: 2
3: 1
2: 1
1: 1

The most freq item value is the first item of desc_keys.

CodePudding user response:

You can use std::map to keep track of the occurrence of the values as shown below:

std::vector<int> vec{1,34,2,44,34,243,5,2,1,554,6,3,7,9,54,643,6,3,2};

//create a mapping from each value to its occurence 
std::map<int, int> countOccurence; 

for(const int& element: vec)
{
    countOccurence[element]  ; //increment the count corresponding to the current value and if the element is not present create it and set the count to corresponding count to 0 automatically
}

Demo

  •  Tags:  
  • c
  • Related