I'm currently teaching myself C++ using Stroustrup's Programming book. Everything has been going well, until now. I'm on the chapter 4 drill, part 6 and have hit a wall.
I need to find the largest value in a vector. I've seen you can use max_element, but would prefer to do it the more basic way first. This is what I have so far, but it doesn't work. Any suggestions?
#include "std_lib_fac.h"
int main()
{ vector<double>vec;
double dig;
while (cin >> dig)
vec.push_back(dig);
double max = 0;
for (double x = 0; x<dig; ++x);
{
if (vec[dig]>max)
max = vec[dig];
}
cout << "The biggest number is: " << max << endl;
if (vec[dig]>max)
You can't use a double as index - use size_t instead.
Normal procedure is to assume the first element of the vector as max and start the loop with the second element.
Thanks for the suggestions. I couldn't get the vectors to work, not sure why. So abandoned this approach and went with simple if clauses:
#include "std_lib_fac.h"
int main()
{
double value = 0;
double max = 0;
double min = 0;
cout << "Enter a value: \n";
while (cin >> value )
{
if (min == 0 && max == 0)
{ min = value;
max = value;
cout << min << " is the smallest.\n"
<< max << " is the largest.\n";
}
else
{
if (value < min)
{
min = value;
cout << value << " is the smallest.\n"
<< max << " is the largest.\n";
}
else
{
if (value > max)
{
max = value;
cout << min << " is the smallest.\n"
<< max << " is the largest.\n";
}
else
{
cout << min << " is the lowest.\n"
<< max << " is the highest.\n";
}
}
}
cout << "Enter another value: ";
}
return 0;
}