|
From: Ioannis V. <no...@ho...> - 2002-05-21 15:02:31
|
I have made a small proggy to assist me to some lottery calculations, it
provides basic statistics. It shows nicely some of the benefits of C++
as a high level programming language, so i decided to post a stripped
down version to the list (in terms of complexity for speed optimization
and bullet-proofness, the results remain the same). Remember, C++ must
be dealt as a high level language, and use low level features only when
you can't do otherwise. This is often missed from the majority of C++
books (mainly written by C coders), mainly because it was very recently
standardised:
#include <iostream>
#include <vector>
int main()
{
using namespace std;
// Ou array where the appearrances of the numbers are recorded
vector<int>stats;
unsigned input;
// cin returns true or false when in a boolean expression
// It returns false when it finds EOF.
while(cin>>input)
{
// The array increases as much as it is required. No overlfows.
if(input>stats.size())
stats.resize(input); // Behavior equivallent to C's realloc()
stats[input-1]++;
}
system("cls");
cout<<endl;
int max=stats[0], min=stats[0];
float sum=0;
// As you see the code is bullet proof, whatever the size becomes
// the code adjusts itself. The size is determined in one place, and
the code
// doesn't depend on a specific number.
for(unsigned long i=0; i<stats.size(); i++)
{
cout<<i+1<<": "<<stats[i]<<"\t";
if(max<stats[i])
max=stats[i];
else if(min>stats[i])
min=stats[i];
sum+=stats[i];
if(!(i%9))
cout<<endl;
}
cout<<endl<<endl;
cout<<"Maximum appearances: "<<max<<", Minimum appearances:
"<<min<<endl;
cout<<"Average appearances: "<<sum/stats.size()<<", Total appearances:
"<<sum;
cout<<endl;
// Array object is destroyed. Its elements destructors are called.
// No explicit memory allocation/deallocation, so no possibility for
memory
// leaks & bugs. ==> Bullet proof code.
}
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.cjb.net
<http://www.noicys.cjb.net/>
* Alternative URL: http://run.to/noicys
|