How to make a program with an array that returns the biigest element in a function?

Can someone make a simple program with an array that will return the biggest element in a function?
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
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.
This is not an assignment. And what is the use of <functional>, <array>, <limits> and template <class 0rd>?
C++ has a function for that, it's called max_element: http://cplusplus.com/reference/algorithm/max_element/

C++ has a function for that, it's called max_element: http://cplusplus.com/reference/algorithm/max_element/

Is there another way to know what the biggest element is?
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
I tried your code, it doesn't work.
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
Topic archived. No new replies allowed.