How is the y.size() = 4 in the following? The values in y are {11, 2, 4, 7} How does one arrive at this? What are a and b in the operator() function for each iteration of the set. I don't understand the construction of y and I can't find anything online that explains this situation. Thank You
#include <iostream>
#include <set>
struct C
{
bool operator()(const int &a, const int &b) const
{
return a % 10 < b % 10;
}
};
int main()
{
std::set<int> x({ 4, 2, 7, 11, 12, 14, 17, 2 });
std::cout << x.size() << std::endl;
std::set<int, C> y(x.begin(), x.end());
std::cout << y.size() << std::endl;
std::set<int>::iterator iter;
for (iter = y.begin(); iter != y.end(); ++iter)
{
std::cout << *iter << std::endl;
}
return 0;
}
Second template argument of set is comparator type — type of functor that implements less operation.
This comparator will compare
a
andb
asa < b
only ifa % 10 < b % 10
, so practically all numbers will be compared by modulo 10.UPDATE:
After pushing into
x
set numbers{ 4, 2, 7, 11, 12, 14, 17, 2 }
, set will contain seven elements{ 2, 4, 7, 11, 12, 14, 17 }
. These elements will be sorted in that way, becauseset
stores objects in sorted way.Then numbers from
x
set are being sequentially inserted intoy
set. Before inserting of each element,set
will find proper place in sorted order of currently inserted numbers. Ifset
will see, that there is already some number on it's place,set
will not insert it.After inserting
{2, 4, 7}
fromx
toy
,y
will be{2, 4, 7}
. Then, to insert11
intoy
set
will do comparisons of11
with{2, 4, 7}
to find proper place using providedC
functor. To check is11
less than2
set
will callC()(11, 2)
, which will result in11 % 10 < 2 % 10
comparison, which will result intrue
, so11
will be inserted before2
.Other numbers from
x
(12, 14, 17
) will not be inserted, becauseset
will find, that12
should be on place of2
(because2 % 10 < 12 % 10 or 12 % 10 < 2 % 10
expression is false, so2 == 12
), and in same way14
and17
.