Apr 29, 2012 at 2:25pm Apr 29, 2012 at 2:25pm UTC
Can someone make a simple program with an array that will return the biggest element in a function?
Apr 29, 2012 at 2:45pm Apr 29, 2012 at 2:45pm UTC
Of course!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <functional>
#include <array>
#include <limits>
#include <iostream>
template <class Ord>
using Function = std::function<Ord(Ord)>;
template <class Ord>
Function<Ord> compose(Function<Ord> f, Function<Ord> g) {
return [f,g](Ord x){return f(g(x));};
}
int main()
{
std::array<int ,5> arr = {42,35,22,72,10};
Function<int > result = [](int x) {return x;};
for (int & x : arr) {
result = compose<int >(result, [x](int y){return x<y ? y : x;});
}
std::cout<<result(std::numeric_limits<int >::min())<<std::endl;
}
In all seriousness though - you won't get a real answer til you've shown that you actually made an attempt at solving the problem yourself.
Last edited on Apr 29, 2012 at 2:49pm Apr 29, 2012 at 2:49pm UTC
Apr 29, 2012 at 4:00pm Apr 29, 2012 at 4:00pm UTC
This is not an assignment.
Then even more so.
And what is the use of <functional>, <array>, <limits> and template <class 0rd>?
The first 3 are headers that I use, the last one is part of a template declaration.
Last edited on Apr 29, 2012 at 4:01pm Apr 29, 2012 at 4:01pm UTC
Apr 29, 2012 at 4:52pm Apr 29, 2012 at 4:52pm UTC
I tried your code, it doesn't work.
Apr 29, 2012 at 5:12pm Apr 29, 2012 at 5:12pm UTC
It does, it just requires a fairly recent compiler with enabled C++11 support. (e.g., g++ 4.6 apparently doesn't like the "using" notation and IIRC VisualC++ 2010 doesn't know the "functional" header, but clang eats the whole thing without complaints).
But that was intentional - determining the maximum element of an collection takes like 4 lines of code, 1 line if you use the <algorithm> header. It's something you can definitely figure out on your own.
Last edited on Apr 29, 2012 at 5:18pm Apr 29, 2012 at 5:18pm UTC