Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the min and max element in vector using std::min_element, std::max_element

Tags:

c++

stl

I am new to C++, and I am trying to find the minimum and maximum elements of a std::vector, but both std::min_element() and std::max_element() are not working together. The given output is only the minimum value. In the output, only the minimum value is printed twice, instead of minimum first then maximum.

#include <iostream> 
#include <algorithm> 
#include <vector>
using namespace std;

bool comp1_(int a, int b) 
{ 
    return a > b; 
}

bool comp2(int a, int b) 
{ 
    return a < b; 
}

int main() 
{ 
    vector<int> myvector;
    vector<int>::iterator i1;
    vector<int>::iterator i2;
    int n, num;
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> num;
        myvector.push_back(num);
    }
    i2 = std::min_element(myvector.begin(), myvector.end(), comp2);
    cout << *i2 << " ";
    i1 = std::max_element(myvector.begin(), myvector.end(), comp1_); 
    cout << *i1; 
    return 0; 
} 
like image 515
Ayush Mishra Avatar asked Jul 12 '26 20:07

Ayush Mishra


1 Answers

Your problem is simply that you use max_element incorrectly. It expects a comparison which returns ​true if the first argument is less than the second. You will need to use comp2_ in both cases. So in your program it should read

i1 = std::max_element(myvector.begin(), myvector.end(), comp2); 

The best practice to achieve what you want is using minmax_element like Jesper mentioned

#include <iostream> 
#include <algorithm> 
#include <vector>


bool compLess(int a, int b)
{
    return (a < b);
}

int main()
{
    using namespace std;
    vector<int> myvector;

    int n, num;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> num;
        myvector.push_back(num);
    }

    auto minmax = std::minmax_element(myvector.begin(), myvector.end(), compLess);
    cout << "min: " << *minmax.first << "\tmax:" << *minmax.second << "\n";
    return 0;
}

With this you do not have to iterate twice through the array.

Hint Do not use using namespace std; in global namespace. I would consider that to be bad practice.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!