![](/img/trans.png)
[英]C++ retrieving an index value in a vector while using min_element or max_element
[英]Index/Max/Min of a Vector<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......";
將每個數字與迄今為止找到的最佳最大值/最小值進行比較。
如果較大/較小,則用最大值/最小值替換並記下索引
您將需要一個max和min變量以及兩個索引-如果將max和min設置為,請謹慎設置初始值
為此,您需要存儲最高和最低元素的索引,並將它們與每次迭代的當前元素進行比較。
// 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";
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.