我希望能够找出向量中的最高和最低元素,并找出当前高/低数字的位置/索引。 例如,
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 :(得分:3)
将每个数字与迄今为止找到的最佳最大值/分钟进行比较 如果它更大/更小用它替换max / min并记下索引
你需要一个max和min变量以及两个索引 - 如果你的最大值和最小值为
,请小心设置初始值答案 1 :(得分: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";
答案 2 :(得分: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