1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <algorithm>
#include <vector>
float max(float a[], int n) // The requirement you were given for this function is dangerous, you have no way to bounds check your array. Oh, and it's not const correct.
{
const std::vector<float> vec(a, a + n); // Generally you should be passing references to std::containers anyway, not pointer-based arrays.
return *std::max_element(vec.begin(), vec.end());
}
float max_better(const std::vector<float>& a, const int n) // It would be much better if your prof had given you this to do!
{
return *std::max_element(a.begin(), a.begin() + n);
}
int main(int argc, char** argv)
{
// What your prof wants your function to call
float arr[] = {1.0, 3.0, 8.0, 3.0,1.0,4.0, 2.0, 9.0, 6.0, 0.0, 5.0};
std::cout << max(arr, 4) << std::endl;
// What would be better
std::vector<float> vec({1.0, 3.0, 8.0, 3.0,1.0,4.0, 2.0, 9.0, 6.0, 0.0, 5.0});
std::cout << max_better(vec, 4) << std::endl;
return 0;
}
|