如何遍历std::vector<uchar>
并计算每个值的出现次数?
我对c++还是个新手,不知道最好的方法是什么
我的猜测是遍历向量,并在一个新的多维向量
中注册每次出现的情况。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
}
那么上面代码中的逻辑是怎样的呢?(如果这是最好的方法?)
我需要找到出现次数最多的值
我们使用unordered_map
作为按键计数器。
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <unordered_map>
#include <vector>
int main(int argc, char const *argv[]) {
auto samples = // or from user input
std::vector<int>{1, 1, 1, 4, 5, 6, 7, 8, 9, 10,
4, 5, 6, 1, 1, 9, 10, 8, 9, 10};
if (samples.size() == 0) {
printf("No samplesn");
}
// counter, key is sample, value is count
std::unordered_map<int, int> counter;
// count samples
for (auto sample : samples) {
counter[sample]++;
}
// sort
std::vector<std::pair<int, int>> sorted_counter;
std::copy(counter.begin(), counter.end(), std::back_inserter(sorted_counter));
std::sort(sorted_counter.begin(), sorted_counter.end(),
[](const std::pair<int, int> &a, const std::pair<int, int> &b) {
// for asc, use a.second < b.second
return a.second > b.second;
});
// print result
for (auto &pair : sorted_counter) {
printf("%d: %dn", pair.first, pair.second);
}
printf("max freq sample: %d, count: %dn", sorted_counter[0].first,
sorted_counter[0].second);
printf("min freq sample: %d, count: %dn",
sorted_counter[sorted_counter.size() - 1].first,
sorted_counter[sorted_counter.size() - 1].second);
return 0;
}
输出:
1: 5
10: 3
9: 3
8: 2
6: 2
5: 2
4: 2
7: 1
max sample: 1, count: 5
min sample: 7, count: 1
频率最高的项值是desc_keys
的第一个项。
您可以使用std::map
跟踪值的出现情况,如下所示:
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
}
演示