且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用自定义比较函数设置构造函数

更新时间:2022-06-26 09:43:19

set 是比较器类型 - 实现较少操作的函子类型。

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

此比较器将比较 a b as a< b 仅当 a%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.

更新:

推入 x 后设置数字 {4,2,7,11,12,14,17,2} $ c>,set将包含七个元素 {2,4,7,11,12,14,17} 。这些元素将以这种方式排序,因为 set 以排序的方式存储对象。

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.

c $ c> x 集正在顺序插入 y 集。在插入每个元素之前, set 将按当前插入数字的排序顺序找到合适的位置。如果设置会看到,它已经有一些数字,设置将不会插入它。

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.

x 中插入 {2,4,7} y y 将为 {2,4,7}
然后,将 11 插入 y >将使用比较 11 {2,4,7} c> C 函子。
检查 11 小于 2 设置将调用 C()(11,2),这将导致 11%10 比较,这将导致 true ,因此 11 2 $ c>

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.

x 因为 set 会找到 12 将不会插入 12,14,17 code>应该位于 2 的位置(因为 2%10 表达式为假,因此 2 == 12 ),同样 14 code> 17

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.