In: Computer Science
C++
For this question alone, put in everything (headers and so on) you need to make it compile. Assume the following functions have already been defined, write a main() that uses them to fill a vector with random integers, remove the smallest and largest integers from the vector, save the result in a file called "trimmed.txt"
void fillRandom(vector & nums, int howMany); // fill with specified number of integers
int minValue(vector nums); // return smallest value in vector
int maxValue(vector <;int> nums); // return largest value in vector
void writeFile(string outFileName, vector nums
); // writes numbers into file
Below is the complete C++ solution. If you face any difficulty while understanding the solution, Please let me know in the comments.
Code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <ostream>
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
// fill with specified number of random integers in vector
void fillRandom(std::vector<int> &nums, int howMan)
{
for(int i=0;i<howMan;i++) {
int num= rand();
nums.push_back(num);
}
}
// return smallest value in vector
int minValue(std::vector<int> nums) {
// find the min value in the vector
int minVal = *min_element(nums.begin(), nums.end());
return minVal;
}
// return largest value in vector
int maxValue(std::vector<int> nums) {
// find the max value in the vector
int maxVal = *max_element(nums.begin(), nums.end());
return maxVal;
}
// Method to write the vector elements in text outFileName
// after removing the minimum and maximum value
void writeFile(string outFileName, std::vector<int> nums)
{
std::ofstream outFile(outFileName);
// get the min and max value of vector
int min = minValue(nums);
int max = maxValue(nums);
// traverse the vector and put the elements excluding
// min and max in trimmed.txt file
for (const auto &num : nums)
if(num != min && num != max)
outFile << num << "\n";
}
int main() {
// declare vector
std::vector<int> nums ;
int howMany = 10;
fillRandom(nums,howMany);
string outFileName = "trimmed.txt";
writeFile(outFileName , nums);
return 0;
}
Output: