min_element help

I have problem understanding the error. Can anyone explain what I did wrong with min-elements on the code below?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <deque>
#include <list>
#include <algorithm>
#include <set>
#include <queue>
#include <vector>
#include <map>
using namespace std;

template<class T>struct Out{
    ostream & out;
    Out(ostream & o):out(o){}
    void operator()(const T & val){out<<val<<" ";}
};
int main(){
    int t[]={1,1,2,2,3,3,4,4,5,5};
    vector<int>v1(t,t+10);
    sort(v1.begin(),v1.end(),greater<int>());
    cout<< min_element(v1.begin(),v1.end()); // my compiler says I have an error on this line, but I don't know what the error is. I was expecting the output to be the smallest value in the array, which is 1. 
//It was not the case. What is wrong with this line?
    return 0;

}
Last edited on
std::min_element() returns an iterator to the element, not the value itself.

So the problem, to explain it simply, is that "cout does not know how to print an iterator".
The solution is to avoid this altogether and print the element (which is what we wanted).

cout<< *min_element(v1.begin(),v1.end());

Edit: don't forget about the Reference section of this site:
http://www.cplusplus.com/reference/algorithm/min_element/
http://www.cplusplus.com/reference/
Last edited on
thank you!
If your compiler says you have an error, it tells you what the error is. If your code has an error in it, it will not compile, so there would be no output.

http://www.cplusplus.com/reference/algorithm/min_element/

std::min_element returns an iterator. std::cout doesn't know what to do with an iterator!

You also need to include <functional> for std::greater.

Of course, there isn't much point in using min_element immediately after you sort a vector. In this case we know the smallest element is returned by v1.back().
Topic archived. No new replies allowed.