簡體   English   中英

我如何知道元素在數組中的位置? C ++

[英]How can I know the position of an element in an array? C++

for(i=0;i<n;i++){
    fin>>x[i];
    if(nrMax<x[i]){
        nrMax=x[i];
    }

}

我怎么知道nrMax在數組中的位置?

如果僅存儲nrMax,則可以使用std::find搜索具有該值的元素,但在顯示的情況下,應擴展內部條件塊以將i的當前值也存儲到變量idxMax

您可以將索引存儲在變量中。

if (n > 0) {
    nrMaxIndex = 0;
    for(i=0;i<n;i++){
        fin>>x[i];
        if(x[nrMaxIndex] < x[i]){
            nrMaxIndex = i;
        }
    }
    nrMax = x[nrMaxIndex];
}
// else handle n==0 situation

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM