c++ vetctor 统计每个值出现次数
时间: 2023-09-02 16:03:46 浏览: 199
统计字符出现次数的C++程序
C语言中,可以使用向量(vector)来统计每个值出现的次数。下面是一个简单实现的示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int value;
int count;
} ValueCount;
int main() {
int num;
printf("请输入要统计的数字个数:");
scanf("%d", &num);
int *numbers = (int*)malloc(num * sizeof(int));
for (int i = 0; i < num; i++) {
printf("请输入第%d个数字:", i + 1);
scanf("%d", &numbers[i]);
}
ValueCount *counts = (ValueCount*)malloc(num * sizeof(ValueCount));
int countSize = 0;
for (int i = 0; i < num; i++) {
int value = numbers[i];
int found = 0;
for (int j = 0; j < countSize; j++) {
if (counts[j].value == value) {
counts[j].count++;
found = 1;
break;
}
}
if (!found) {
counts[countSize].value = value;
counts[countSize].count = 1;
countSize++;
}
}
printf("每个值出现的次数如下:\n");
for (int i = 0; i < countSize; i++) {
printf("值:%d,出现次数:%d\n", counts[i].value, counts[i].count);
}
free(numbers);
free(counts);
return 0;
}
```
以上代码通过向量`ValueCount`的方式,统计用户输入的数字数组中,每个值出现的次数,并输出结果。程序首先要求用户输入要统计的数字个数,然后逐个输入这些数字,然后遍历数字数组,对每个值进行统计,通过向量`ValueCount`来记录每个值出现的次数。最后打印出每个值和对应的出现次数。
阅读全文