2014-01-24 82 views
1

我希望能夠找出矢量中的最高和最低元素,並找出當前高/低數字的位置/索引。 例如,矢量的索引/最大值/最小值<double> C++

vector<double> x; 
std::cout << "Enter in #s: "; 
double numbers; 
std::getline(std::cin, numbers); 
x.push_back(numbers); 

比方說,用戶輸入4.3 1.0 2.99 43.5

我想要的結果說

The highest number is 43.5 at position 4 
The lowest number is 1.0 at position 2 

我想知道是否有任何的方式來實現這個代碼不使用min_element/max_element函數並使用for循環執行它?

我想用這樣的:

for (int i=0;i < x.size();i++) 
    if (//the number is less than) { 
     std::cout << "The lowest number is...... at position ....."; 
    if (//the number is greather than) { 
     std::cout << "The highest number is......at position......"; 
+0

哇,他們是awefully接近。 – RichardPlunkett

回答

2

爲此,您需要存儲最高和最低元素的索引,並將它們與每次迭代的當前元素進行比較。

// Note: the below code assumes that the container (vector) is not empty 
// you SHOULD check if the vector contains some elements before executing the code below 

int hi, lo; // These are indices pointing to the highest and lowest elements 
hi = lo = 0; // Set hi and lo to the first element's index 

// Then compare the elements indexed by hi and lo with the rest of the elements 
for (int i = 1;i < x.size();i++) { 
    if(x[i] < x[lo]) { 
     // The element indexed by i is less than the element indexed by lo 
     // so set the index of the current lowest element to i 
     lo = i; 
    } 
    // Below, else if is used and not if because the conditions cannot be both true 
    else if(x[i] > x[hi]) { 
     // Same logic as the above, only for the highest element 
     hi = i; 
    } 
} 

// Note: the position indicated by the output below will be 0-based 
std::cout << "The lowest number is " << x[lo] << " at position " << lo << ".\n"; 
std::cout << "The highest number is " << x[hi] << " at position " << hi << ".\n"; 

LIVE DEMO

3

比較每一個數目最好最大/最小迄今發現的。
如果是大/小用它代替最大/最小,並注意指數

您將需要一個最大值和最小值變量,兩個指標 - 要小心什麼你,如果你的最高設置的初始值和分鐘

0
size_t iMax=0,iMin=0; 
    for(size_t i=1; i<x.size(); ++i) 
    { 
      if(x[iMax] < x[i]) 
        iMax=i; 
      if(x[iMin] > x[i]) 
        iMin=i; 
    } 
    //iMax is index of the biggest num in the array