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;
}
max_elementis returning the wrong value. From cppreference: "... returns trueif the first argument is less than the second." Your comparer is doing the opposite.