Please help me understand "set"

I have know idea how this program works and it was a question in a past exam. Can you please provide a link to a guide or a walk through of how this program returns: 50 30 20 10 .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream> 
#include <set> 
using namespace std;

int main()
{
set<int, greater<int> > myset;		
myset.insert(50);	myset.insert(10);	myset.insert(30);
myset.insert(10);	myset.insert(20);	
set<int, less<int> >::iterator	p=myset.begin();
while(p != myset.end())		
{			
cout << *p << ' '; p++;
}

cout << endl; return 0;
}
std::set<> holds an ordered set of unique objects.
The ordering is based on the comparison predicate - in this example, std::greater<int>

The ordering imposed by std::greater<int> is that if a compares greater than b - a>b is true - a would appear before b in the ordered sequence. Therefore, the integers in the set are held in descending order 50 30 20 10.
Fascinating, that one:
1
2
3
4
5
typedef set<int, greater<int> > T;
typedef set<int, less<int> > U;

T myset;
U::iterator p = myset.begin();

g++-4.8.1 -Wall -Wextra -pedantic -std=c++11

Does not even comment the apparent type mismatch. Therefore, iterator does not care really about the comparator.
> Therefore, iterator does not care really about the comparator.

In almost every C++11 implementation, the iterators are SCARY iterators.
See: http://blogs.msdn.com/b/vcblog/archive/2012/04/06/10291485.aspx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/////////////// SCARY iterators check /////////////////////////

#include <iostream>
#include <iterator>
#include <set>
#include <functional>
#include <type_traits>
#include <boost/pool/pool_alloc.hpp>

int main()
{
    using set_one = std::set<int> ;

    // container with different comparator, different allocator
    using set_two = std::set< int, std::greater<int>, boost::pool_allocator<int> > ;

    constexpr bool cntrs_of_same_type = std::is_same< set_one, set_two >::value ;
    std::cout << "containers are of same type? " << std::boolalpha
               << cntrs_of_same_type << '\n' ; // false

    using iter_one = set_one::iterator ;
    using iter_two = set_two::iterator ;

    // is iter_type_one the same as iter_type_two?
    constexpr bool iters_of_same_type = std::is_same< iter_one, iter_two >::value ;
    std::cout << "SCARY iterators? " << iters_of_same_type << '\n' ; // true
}

http://coliru.stacked-crooked.com/a/eebaf2406e18b08a
Topic archived. No new replies allowed.