set constructor with custom compare function

2019-04-17 06:27发布

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;
}

标签: c++ set compare
1条回答
劫难
2楼-- · 2019-04-17 06:51

Second template argument of set is comparator type — type of functor that implements less operation.

struct C
{
    bool operator()(const int &a, const int &b) const
    {
        return a % 10 < b % 10;
    }
};

This comparator will compare a and b as a < b only if a % 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, because set stores objects in sorted way.

Then numbers from x set are being sequentially inserted into y set. Before inserting of each element, set will find proper place in sorted order of currently inserted numbers. If set will see, that there is already some number on it's place, set will not insert it.

After inserting {2, 4, 7} from x to y, y will be {2, 4, 7}. Then, to insert 11 into y set will do comparisons of 11 with {2, 4, 7} to find proper place using provided C functor. To check is 11 less than 2 set will call C()(11, 2), which will result in 11 % 10 < 2 % 10 comparison, which will result in true, so 11 will be inserted before 2.

Other numbers from x (12, 14, 17) will not be inserted, because set will find, that 12 should be on place of 2 (because 2 % 10 < 12 % 10 or 12 % 10 < 2 % 10 expression is false, so 2 == 12), and in same way 14 and 17.

查看更多
登录 后发表回答