histo.cpp

来自「一本全面剖析C++数据结构算法的书籍」· C++ 代码 · 共 40 行

CPP
40
字号
// histogramming#include <iostream.h>#include <stdlib.h>#include "xcept.h"void main(void){// Histogram of nonnegative integer values.   int n,  // number of elements       r;  // values between 0 and r   cout << "Enter number of elements and range"        << endl;   cin >> n >> r;   // create histogram array h   int *h;   try {h = new int[r+1];}   catch (NoMem)      {cout << "range is too large" << endl;       exit(1);}   // initialize array h to zero   for (int i = 0; i <= r; i++)      h[i] = 0;   // input data and compute histogram   for (int i = 1; i <= n; i++) {      int key;  // input value      cout << "Enter element " << i << endl;      cin >> key;      h[key]++;      }   // output histogram   cout << "Distinct elements and frequencies are"        << endl;   for (int i = 0; i <= r; i++)      if (h[i]) cout << i << "   "  << h[i] << endl;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?