C++ convert double values to a map with value counts
Here is an example code that converts an array of double values to a map with value counts in C++:
#include <iostream>
#include <map>
int main() {
double arr[] = {1.2, 3.4, 4.5, 1.2, 2.3, 4.5, 1.2, 3.4};
int n = sizeof(arr) / sizeof(arr[0]);
std::map<double, int> value_counts;
for (int i = 0; i < n; i++) {
if (value_counts.find(arr[i]) == value_counts.end()) {
value_counts[arr[i]] = 1;
} else {
value_counts[arr[i]]++;
}
}
for (auto it = value_counts.begin(); it != value_counts.end(); it++) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
In this code, we first define an array arr of double values and determine its length n. We then create an empty map value_counts with keys of type double and values of type int.
We loop through the array arr, and for each value, we check if it already exists in the map by using the find function. If it doesn't exist, we add it to the map with a count of 1. If it does exist, we increment its count by 1.
Finally, we loop through the map and print out each key-value pair, where the key is the double value and the value is its count
原文地址: https://www.cveoy.top/t/topic/g88I 著作权归作者所有。请勿转载和采集!