C++ double array to map counts
Here is an example of converting a C++ double array to a map of counts:
#include <iostream>
#include <map>
int main() {
double arr[] = {1.3, 2.6, 1.3, 4.2, 2.6, 2.6};
int size = sizeof(arr) / sizeof(arr[0]);
std::map<double, int> counts;
for (int i = 0; i < size; i++) {
counts[arr[i]]++;
}
for (auto const& pair : counts) {
std::cout << pair.first << " appears " << pair.second << " times." << std::endl;
}
return 0;
}
In this example, we first define a double array arr with some sample values. We then determine the size of the array using sizeof and divide by the size of a single element to get the number of elements in the array.
Next, we define a std::map<double, int> called counts to hold our counts. We loop through the array and use the [] operator of the map to increment the count for each element. If the element doesn't exist in the map yet, it will be created with a count of 0 before being incremented.
Finally, we loop through the map and print out each element along with its count. The output of this program would be:
1.3 appears 2 times.
2.6 appears 3 times.
4.2 appears 1 times.
This shows that the double array has been successfully converted to a map of counts
原文地址: https://www.cveoy.top/t/topic/g88P 著作权归作者所有。请勿转载和采集!