C++ Primer第五版学习笔记六 控制流之if语句

统计输入中每个值出现的次数(没有实现间隔重复数的统计,例如:输入 1 1 2 1,结果是1的个数2,2的个数1,1的个数1),以后可以用map等数据结构实现

#include <iostream>

int main() {
    int currentVal; // 正在统计的数
    int val; // 读入的值
    
    if (std::cin >> currentVal) {
        int count = 1; // 保存当前值个数
        while (std::cin >> val) {
            if (val == currentVal) {
                ++count;
            }
            else {
                std::cout << currentVal << "的个数:" << count << std::endl;
                count = 1;
                currentVal = val;
            }
        }
        // 打印最后一个值的个数
        std::cout << currentVal << "的个数:" << count << std::endl;
    }

    return 0;
}
原文地址:https://www.cnblogs.com/liyunfei0103/p/9090725.html