3

I have tried to use the max function but it needs a iterator and that are A.begin and A.end but for my program I want to find for a range say from i to x .I tried to read the docs but was unable to find the solution. Any help would be appreciated.Thank you.

Uwpbeginner
  • 405
  • 4
  • 15
  • 5
    vector provides random access iterators so you can easily convert index to iterator `items.begin() + i` – user7860670 Jul 20 '17 at 09:20
  • It would be better if you could provide some real code – fitzbutz Jul 20 '17 at 09:20
  • 1
    That's the good thing about all the [standard algorithm functions](http://en.cppreference.com/w/cpp/algorithm), they take a *range*. Iterators doesn't have to be just the beginning and end, it can be anything in between. – Some programmer dude Jul 20 '17 at 09:21
  • Possible duplicate of [Can I increment an iterator by just adding a number?](https://stackoverflow.com/questions/1033089/can-i-increment-an-iterator-by-just-adding-a-number) – Andre Kampling Jul 20 '17 at 09:22

1 Answers1

9

You're not looking for max. But for std::max_element.

To use it:

std::vector<int> v;
// fill it
auto max_it = std::max_element(v.begin()+i, v.end());

And to check in the range [i,j):

auto max_it = std::max_element(v.begin()+i, v.begin()+j);

max_it here is an iterator, to get the number from it:

int max_number = *max_it;
The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189