Max In a C++ Array

后端 未结 3 1500
傲寒
傲寒 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 
    #include 
    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.

提交回复
热议问题