Max In a C++ Array

后端 未结 3 1499
傲寒
傲寒 2021-02-05 20:31

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

相关标签:
3条回答
  • 2021-02-05 20:45

    Here is a modification of your program that does what you want:

    #include <iostream>
    #include <algorithm>
    using namespace std;
    int main()
    {
        int array[11];
        int n = 11;
        for (int i = 0; i < n; i++) {
            array[i] = i;
        }
        array[5] = 5000;
    
        cout << *std::max_element(array, array + n) << "\n";
    
        return 0;
    }
    

    Note that you had a bug in your program, you did not initialize the last element in your array. This would cause your array to contain junk value in the last element. I've fixed that by increasing n to 11. Note that this is OK because the condition in the for loop is i < n, which means that i can be at most 10, which is what you want.

    0 讨论(0)
  • 2021-02-05 21:01

    You can also use std::array by #include<array>

    #include <iostream>
    #include <algorithm>
    #include <array>
    using namespace std;
    int main()
    {
    array<int,10> arr;
    int n = 10;
    for (int i = 0; i < n; i++) {
    arr[i] = i;
    }
    arr[5] = 5000;
    
    
    cout<<"Max: "<< *max_element(arr.begin(),arr.end())<<endl;
    
    
    for (int i = 0; i < n; i++)
    cout << arr[i] << " ";
    return 0;
    }
    

    More info on std::array

    0 讨论(0)
  • 2021-02-05 21:06

    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

    0 讨论(0)
提交回复
热议问题