Resorter
Resorter

Reputation: 317

how to find the max element between the m-th and the n-th element of a vector in C++?

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.

Upvotes: 2

Views: 248

Answers (2)

sjrowlinson
sjrowlinson

Reputation: 3355

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.

Upvotes: 5

Brian Bi
Brian Bi

Reputation: 119184

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.

Upvotes: 2

Related Questions