http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
Chapter 8 // Exercise 10
10. Write a function maxv() that returns the largest element of a vector argument.
#include "stdafx.h" #include "std_lib_facilities.h" double maxv(const vector<double>& v) { //if vector only has 1 value return that if (v.size() == 1) return v[0]; //make first value in vector max value double largest = v[0]; //go through every value, if the next value is bigger //than the last, make that the new max value for (int i = 0; i < v.size(); ++i) { if (largest < v[i]) largest = v[i]; } return largest; } int main() { vector<double> numbers = { 1000, 6, -12, 700, 56, 89, -900, 1 }; double max = maxv(numbers); cout << max << endl; keep_window_open(); return 0; }
At first I tried to use the max_element() function however it didn't seem to like working with vectors, so I used the template code to draft this function. It was a lot simpler than I initially thought. Since Bjarne didn't specify a data type I went with double however you can easily change the data type yourself.
I found this way a little easier to compute the largest value. Let me know what you think:
ReplyDelete#include
#include
#include
#include
using namespace std;
void error(string s) {
throw runtime_error(s);
}
void set_max(vector& maxv1) { // add elements into a vector
double dig = 0.0;
cout << "Please enter some integers. Enter 'n' when completed.\n";
while (cin >> dig) {
maxv1.push_back(dig);
}
if (maxv1.size() == 0) {
error("There needs to be at least one element inside the vector.");
}
}
void get_max(vector& maxv2) { // print the largest element inside the vector
sort(maxv2.begin(), maxv2.end()); // sort the elements from smallest to largest
string label = "The largest element is ";
cout << label << maxv2[maxv2.size() - 1]; // print out the last element of the vector
}
int main() {
vector maxv;
set_max(maxv);
get_max(maxv);
return 0;
}
Yep! I forgot sort was in std_lib_facilities, back then I wasn't use to using standard library functions; I always forgot it was there lol.
DeleteOh wow, did not think you would respond since this has been up for a few years. If you don't mind, is there anyway I could contact you? Curious how you were able to balance everything
ReplyDeleteI keep this blog active, it's become my dumping ground for personal dev work. I do check for comments every few days or so but if you want, you can email me at helluvablog@hotmail.com
Delete