I'm writing a program to read a sequence of doubles into a vector, prints the values, the sum of the values, and finds and prints the smallest and greatest value. I want to use the sort algorithm to find the smallest and greatest value but I keep getting errors when I attempt it. Any help is greatly appreciated.
#include "iostream"
#include "string"
#include "vector"
#include "algorithm"
#include "cmath"
usingnamespace std;
class KeepRunning {
public:
~KeepRunning() {
// Whatever code you prefer to keep the program running, e.g.
cout << endl << endl;
system("pause"); // "Press enter"
}
};
int main()
{
KeepRunning kr; // needed to halt the program.
vector <double> v;
double sum = 0;
double smallest = 0;
double greatest = 0;
int i = 0;
cout << "enter a few distances between two cities along a given route:\n";
for(double x; cin >> x; )
{
v.push_back(x);
}
// calculate the sum of the distances between cities.
for (i = 0; i < v.size(); ++i)
{
sum += v[i];
}
cout << "\nSum = " << sum << " miles" << endl;
// calculate the mean distance between cities.
cout << "Mean distance between cities = " << sum / v.size() << endl;
// print the smallest and greatest distance between cities.
sort(v);
}
sort() takes two arguments. An iterator to the first element, and an iterator to the last element. It would loop like this for you sort (v.begin(), v.end())