Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max In a C++ Array

Tags:

c++

arrays

I am trying to find the 'biggest' element in a user made array ,by using the max function from the algorithm library/header.

I have done some research on the cplusplus reference site but there I only saw how to compare two elements using the max function. Instead I am trying to display the maximum number using a function 'max' ,without having to make a 'for' loop to find it.

For example:

Array: array[]={0,1,2,3,5000,5,6,7,8,9} Highest value: 5000

I have made this code but it gives me a bunch of errors, which can be the issue?

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int array[11];
    int n = 10;
    for (int i = 0; i < n; i++) {
       array[i] = i;
    }
    array[5] = 5000;
    max(array , array + n);
    for (int i = 0; i < n; i++)
        cout << array[i] << " ";
    return 0;
}
like image 238
JohnnyOnPc Avatar asked Dec 16 '15 14:12

JohnnyOnPc


People also ask

What is max size of array in C?

The maximum allowable array size is 65,536 bytes (64K). Reduce the array size to 65,536 bytes or less. The size is calculated as (number of elements) * (size of each element in bytes).

What is Max value in array?

M = max( A ) returns the maximum elements of an array. If A is a vector, then max(A) returns the maximum of A . If A is a matrix, then max(A) is a row vector containing the maximum value of each column of A .


1 Answers

max_element is the function you need. It returns an iterator to the max element in given range. You can use it like this:

cout << " max element is: " << *max_element(array , array + n) << endl;

Here you can find more information about this function: http://en.cppreference.com/w/cpp/algorithm/max_element

like image 83
Ardavel Avatar answered Oct 30 '22 04:10

Ardavel