In: Computer Science
C++
Vectors.
Create a program do the following in the program:
1. declare an vector without specifying the size
2. use push_back to add random integers between 100 and 999 to the vector
3. write a function that returns the smallest, largest, and average of the numbers in the vector
display the smallest, largest, and average of the numbers in the vector
output: smallest, largest, average in respective order
#include <bits/stdc++.h>
#include <cstdlib>
#include <ctime>
using namespace std;
class values{
public:
int smallest;
int largest;
int average;
};
values myfunc(vector<int> &v){
auto n = v.size();
values stats;
stats.smallest = *min_element (v.begin(), v.end()); //stl function to find minimum element
stats.largest = *max_element (v.begin(), v.end()); //stl function to find maximum element
//accumulate does the sum of elements in vector and then to get avg we will devide it with vector size
stats.average = accumulate( v.begin(), v.end(), 0.0) / n;
return stats;
}
int main() {
vector<int> v;
int num;
int count = 1000000; // number of elements we want to push in vector
// This program will create different sequence of
// random numbers on every program run
// Use current time as seed for random generator
srand(time(0));
//rand() % x generates the number between 0 and x [excluding x]
// so for number between 100 and 999 we will add 101 to
while(count--) {
num = 101 + rand() % 898;
v.push_back(num);
}
values v_stats;
v_stats = myfunc(v);
cout << v_stats.smallest << " " << v_stats.largest << " " << v_stats.average;
return 0;
}