繁体   English   中英

查找数组中最大元素的最大索引(C++)

[英]Find the largest index of the largest element in an array (C++)

我有一个从 0 到 9 的随机整数生成的数组,我有一个 function 可以做到这一点。 我还有一个 function 可以确定数组中的最大元素是什么。 我需要编写另一个 function 来确定最大变量的索引。 我相信问题是我不能在 function 中调用 function 但它可能是别的东西。

我的代码如下:

#include <iostream>
#include <ctime>
#include <time.h> 

using namespace std;

void initialize(int arr[], int size);

void print(int arr[], int size);

void findLargest(int arr[], int size);

void largestIndex(int arr[], int size);


int main(){


    const int SIZE = 10;
    int myList[SIZE];

    initialize(myList, SIZE);

    print(myList, SIZE);

    findLargest(myList, SIZE);


    largestIndex(myList, SIZE);
    
    return 0;

}


void initialize(int arr[], int size){
    
    srand(time(0));

    for(int i = 0; i < size; i++){

        arr[i] = (rand() % 10);
     }
}
 

void print(int arr[], int size){
       for(int j = 0; j < size; j++){
        
        cout<<arr[j]<< endl;
    }
}


void findLargest(int arr[], int size){
    for(int i = 0; i < size; i++){

       if(arr[0] < arr[i])
           arr[0] = arr[i];
    }
    cout << "The largest element in the array is " << arr[0]<< endl;;
}


void largestIndex(int arr[], int size){

    for(int i = 0; i < size; i++){
        if(arr[i] == 9){
            cout<< "The index of the largest element is " + i <<endl;
        }

    }
}

通过编译器资源管理器运行它

https://godbolt.org/z/c9ETjaq3z

显示此错误消息

<source>:69:59: warning: adding 'int' to a string does not append to the string [-Wstring-plus-int]
            cout<< "The index of the largest element is " + i <<endl;
                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
<source>:69:59: note: use array indexing to silence this warning
            cout<< "The index of the largest element is " + i <<endl;
                                                          ^
                   &                                      [  ]

这条线

 cout << "The index of the largest element is " + i <<endl;

i添加到指向字符串"The index of the largest element is "的指针。 结果是您雕刻了字符串的开头而不是显示 i 的值。

你想要的是

 cout << "The index of the largest element is " << i <<endl;

或者

 cout << "The index of the largest element is " + std::to_string(i) <<endl;

您可能要考虑使用std::max_element

auto largest = *std::max_element(arr, arr + size);
std::cout << "Largest... = " << largest << std::endl;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM