Hi. I am last year BSc(I.T) student. In my last lecture sir give the assignment on max_element() function. I tried different solution but none of them worked out .any suggestion would be highly appreciated.
Hi. I am last year BSc(I.T) student. In my last lecture sir give the assignment on max_element() function. I tried different solution but none of them worked out .any suggestion would be highly appreciated.
I suggest you to refer following example of max_element() function, which will give you something idea about the use of this function:
Output:Code:int array[] = { 3, 1, 4, 1, 5, 9 }; unsigned int array_size = sizeof(array) / sizeof(array[0]); cout << "Max element in array is " << *max_element(array, array+array_size) << endl; vector<char> v; v.push_back('a'); v.push_back('b'); v.push_back('c'); v.push_back('d'); cout << "Max element in the vector v is " << *max_element(v.begin(), v.end()) << endl;
Code:Max element in array is 9 Max element in the vector v is d
Prototype
Max_element is an overloaded name; there are in fact two max_element functions.
template <class ForwardIterator>
ForwardIterator max_element(ForwardIterator first, ForwardIterator last);
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator max_element(ForwardIterator first, ForwardIterator last,
BinaryPredicate comp);
Description
Max_element locates the largest element in the range [first, last). It returns the first iterate i in [first, last) such that no other iterate in [first, last) points to a value greater than *i. The return value is last if and only if [first, last) is an empty range.
The two versions of max_element be different in how they define whether one element is less than another. The first version compares objects using operator<, and the second compares objects using a function object comp.
The first version of max_element returns the first iterator i in [first, last) such that, for each iterate j in [first, last), *i < *j is false. The second version returns the first iterate i in [first, last) such that, for every iterate j in [first, last), comp(*i, *j) is false.
Requirements on types
For the first version:
• ForwardIterator is a model of Forward Iterator.
• ForwardIterator's value type is LessThan Comparable.
For the second version:
• ForwardIterator is a model of Forward Iterator.
• BinaryPredicate is a model of Binary Predicate.
• ForwardIterator's value type is convertible to BinaryPredicate's first argument type and second argument type.
Preconditions
• [first, last) is a valid range.
Complexity
Linear. Zero comparisons if [first, last) is an empty range, otherwise exactly (last - first) - 1 comparisons.
Code:int main() { list<int> L; generate_n(front_inserter(L), 1000, rand); list<int>::const_iterator it = max_element(L.begin(), L.end()); cout << "The largest element is " << *it << endl; }
Bookmarks