2

It seems that the function max_element for vector would work for this purpose but I am not sure how to use it.

ForwardIterator max_element (ForwardIterator first, ForwardIterator last);

What is the type of ForwardIterator? How do I specify that it searches starting from the m-th element? And how do I find the index of the max element? Thanks.

Resorter
  • 307
  • 3
  • 9

2 Answers2

5

Use the following:

std::max_element(vec.begin() + m, vec.begin() + n);

assuming m < n and n <= vec.size(), where vec is a std::vector object.

This will return an iterator to the max-value element in the specified range, to get the corresponding index use it - vec.begin() where it is the max-element iterator.

sjrowlinson
  • 3,297
  • 1
  • 18
  • 35
2

This signature is telling you that std::max_element is a template that accepts arguments of any type so long as it meets the forward iterator requirements, and it returns the same type. You would simply pass in the iterators and it would return an iterator to the maximum element found in the range. You can dereference that to get the value itself. Hence

const auto max_iterator = std::max_element(v.begin() + m, v.begin() + n);
const auto max_value = *i;

Care must be taken to avoid the case where m is greater than or equal to n.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312