vector exercise

Basic Statistics Again -- with Array and Vector

Overview

Given a list of N floating point numbers, find the mean, maximum, minimum,  root-mean-square and standard deviation. Your program will first ask for N, the number of integers in the list, which the user will input. Then the user will input N more numbers.  You need to use array and vector to store the numbers and use functions for each calculation.

<< the array implementation is in another page >>

The same problem was addressed with array implementation earlier.  If you have not done that, I highly recommend do that one first.  In the vector approach, I use a simple main routine to initialize the test vector.  Then, it calls two statistics routines.

#include <iostream>

#include <vector>

using namespace std;

double CalculateMax(vector <int>&);

void MinMaxMean(vector <int>&, double&, double&, double&);

int main() {

vector<int> myvector;

myvector.push_back(4);

myvector.push_back(7);

myvector.push_back(3);

cout << CalculateMax(myvector)<< endl;

double small, large, avg;

MinMaxMean(myvector, small, large, avg);

cout << "Min=" << small << "\t Max=" << large << "\t Mean=" << avg << endl;

}

--------------

Implementations of two statistics routines follows:

#include <vector>

using namespace std;

double CalculateMax(vector<int>& data) {

double max = 0;

for (unsigned int i=0; i < data.size(); i++) {

if (data[i] > max) max = data[i];

}

return max;

}

void MinMaxMean(vector<int>& data, double& min, double& max, double& mean) {

double sum=0;

min=INT_MAX;

max=INT_MIN;

if (data.size()==0) { min = max = mean = 0; return; }

for (unsigned int i=0; i<data.size(); i++) {

sum += data[i];

if (data[i] < min) min = data[i];

if (data[i] > max) max = data[i];

}

mean = sum / data.size();

}

Discussions: