2016-10-04 69 views
0

我知道這些問題已經回答了死亡,但我必須在某些限制下執行這些問題。我是C++的新手,爲了適應新的語言,我只做了一些練習。從矢量C++中查找最高和最低元素的索引

首先,我有一個vector<int> pricelist{12,32,43,23,54}元素值和元素數量,不要緊,因爲它會根據測試而變化。它位於Test.cpp,它將檢查是否符合要求。因此,在這種情況下,測試將檢查以查看price.getlowestPrice == 0price.gethighestPrice == 4

我有頭文件我需要工作,在它的代碼組成,

class Prices{ 
protected: 
    int highestPrice; 
    int lowestPrice; 

public: 

Trade(const int highPriceIn, const int lowPriceIn) 
    : highestPrice(highPriceIn), lowestPrice(lowPriceIn) { 
} 

int getllowestPrice() const { 
    return lowestPrice; 
} 

int gethighestPrice() const { 
    return highestPrice; 
    } 

}; 

我顯然非常無能(因爲你很快就會看到)上(C++的語法或一般我編碼猜)我嘗試創建一個方法來查找最小和最大值,並返回索引,但我不知道正確的方式去做(沒有添加一個返回,因爲我不知道該返回什麼)。

int lowNhightPrices(vector<int> prices) { 
int min, max; 
    max = min = 0; 
    int currentState; 
    for (int i = 0; i < prices.size(); ++i) { 

     { 
      if (prices[i] < prices[min]) 
      { 
       min = i; 
      } 
      else if (prices[i] > prices[max]) 
      { 
       max = i; 
      } 
+1

有什麼限制? –

+0

可能是像['std :: upper_bound'](http://en.cppreference.com/w/cpp/algorithm/upper_bound)? –

+3

你在尋找['std :: minmax_element'](http://en.cppreference.com/w/cpp/algorithm/minmax_element)嗎? – NathanOliver

回答

0

lowNhightPrices可以返回最小值和最大值,或者最小值和最大值本身的任一的索引。無論哪種方式,您都可以使用std::pair<int, int>作爲返回類型。

std::pair<int, int> lowNhightPrices(vector<int> const& prices) { 
    ... 
    // Return the values. 
    // return {minValue, maxValue}; 

    // Or, return the indices. 
    return {minIndex, maxIndex}; 
} 
+0

只是一個問題......是我的循環搜索正確的最小值/最大值?還是完全錯誤? – LovesPie

+0

@LovesPie,這段代碼對我來說確實很好。 –