I want to be able to figure out the highest and lowest element in an vector<double> and also figure out what position/index that high/low number is currently.
For example,
The highest number is 43.5 at position 4
The lowest number is 1.0 at position 2
I was wondering if there is any way to implement this code WITHOUT using the min_element/max_element function and do it with a for loop?
I wanted to use something like:
1 2 3 4 5
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......";
#include <iostream>
#include <vector>
int main()
{
std::vector<int> nums = {3, 1, 4, 2};
int minPos = 0, maxPos = 0;
for (unsigned i = 0; i < nums.size(); ++i)
{
if (nums[i] < nums[minPos]) // Found a smaller min
minPos = i;
if (nums[i] > nums[maxPos]) // Found a bigger max
maxPos = i;
}
std::cout << "Min is " << nums[minPos] << " at position " << minPos;
std::cout << "\nMax is " << nums[maxPos] << " at position " << maxPos;
}