如何遍歷 astd::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
}
上面的代碼中的邏輯是什么樣的?(如果這是最好的方法?)
我需要找到出現次數最多的值
uj5u.com熱心網友回復:
我們使用 anunordered_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 samples\n");
}
// 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: %d\n", pair.first, pair.second);
}
printf("max freq sample: %d, count: %d\n", sorted_counter[0].first,
sorted_counter[0].second);
printf("min freq sample: %d, count: %d\n",
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
。
uj5u.com熱心網友回復:
您可以使用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
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/470088.html
標籤:C