'How do I find the max element in a vector (C++)?

Here's my code. I omitted the code for the vector because it wasn't important.

#include <string>
#include <iostream>
#include <vector>
using namespace std;


int main() {
    vector<int> scores;

    // code to make vector

    cout << "High score: " << scores[std::max(scores.begin(), scores.end())] << endl;
    system("pause");
}

It is my understanding that std::max returns a iterator, but I don't really know what to do with the iterator. I've seen the example

*max(scores.begin(), scores.end())

to get it to return an index instead of a iterator, but it get the error

Expression: vector iterator not dereferencable

I tried using the iterator and then using std::distance

vector<int>::iterator high = std::max(scores.begin(), scores.end());
cout << "High score: " << scores[std::distance(scores.begin(), high)] << endl;

but I get the error

Expression: vector subscript is out of range. 

What would be the best way to solve this problem?



Solution 1:[1]

There is standard algorithm named std::max_element declared in header <algorithm> that does what you need.

For example

#include <algorithm>

//...

cout << "High score: " << *std::max_element( scores.begin(), scores.end() ) << endl;

It is assumed that the vector is not empty.

As for this call

std::max(scores.begin(), scores.end())

then it returns maximum iterator among these two iterators. And the iterator that corresponds to end() is always greater than or equal to (if the vector is empty) the iterator that corresponds to begin().

Solution 2:[2]

Best way is to use max_element:

vector<int> scores;
//input
vector<int>::iterator it;
it=max_element(scores.begin(),scores.end());
cout<<*it;

If you want the max without any concern of time complexity you can also use this (not advisable though):

sort(scores.begin(),scores.end());
cout<<scores[scores.size()-1];

You must use the first way only!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 moovon