gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:18:11 25 4
gpt4 key购买 nike

下面的 y.size() = 4 是怎么来的? y 中的值是 {11, 2, 4, 7} 如何得到这个?集合的每次迭代的 operator() 函数中的 a 和 b 是什么。我不明白 y 的构造,我在网上找不到任何解释这种情况的东西。谢谢你

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

最佳答案

set 的第二个模板参数是比较器类型——实现较少操作的仿函数类型。

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

这个比较器将比较ab作为a < b仅当a % 10 < b % 10 , 所以实际上所有数字都将通过模 10 进行比较。

更新:

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

然后数字来自 x set 被顺序插入 y放。在插入每个元素之前,set将按照当前插入的数字的排序顺序找到合适的位置。如果set会看到,它的位置上已经有一些数字,set不会插入它。

插入后{2, 4, 7}来自 xy , y将是 {2, 4, 7} .然后,插入 11进入y set将对 11 进行比较与 {2, 4, 7}使用提供的 C 找到合适的位置仿函数。要检查的是 11小于 2 set会调用C()(11, 2) ,这将导致 11 % 10 < 2 % 10比较,这将导致 true , 所以 11将插入 2 之前.

来自 x 的其他号码( 12, 14, 17 ) 不会被插入,因为 set会发现,12应该代替2 (因为 2 % 10 < 12 % 10 or 12 % 10 < 2 % 10 表达式是假的,所以 2 == 12 ),并且以同样的方式 1417 .

关于c++ - 使用自定义比较函数设置构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com