how do i find the maximum of an list?

list is randomized

i cannot use the sort function
and my list is dynamically allocated
1
2
3
4
5
6
//this is what i tried
max = myList.front();     //first element

/*
how do i compare it to the list and assign if it is true
*/
Last edited on
is there another way?
is there another way?


This being CPP there is (almost) always another way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# include <iostream>
# include <list>
# include <iterator>

template <typename T>
auto listMax(const std::list<T>& myList)
{
    auto list_maximum = *(myList.cbegin());

    for (auto itr = std::next(myList.cbegin()); itr != myList.cend(); ++itr)
    {
       list_maximum = ((*itr > list_maximum )? *itr : list_maximum);
    }
    return list_maximum;
}

int main()
{
    std::list<int> myList{1, 3, 2, 4, 9, 5, 6, 8};
    auto list_maximum = listMax(myList);
    std::cout << list_maximum << "\n";
}
Last edited on
Topic archived. No new replies allowed.