class MyCriterion {public: bool operator()(const Employee& e1,const Employee& e2)const {return e1.age<e2.age;}//排列 }; template <class Iterator,class C> Iterator max(Iterator first,Iterator last,C cmp) { Iterator m=first; for(++first;first!=last;++first) if(cmp (*m,*first))// ③ //函数对象使用 m=first; return m; }解释这段代为什么cmp中要使用指针
时间: 2024-03-31 21:38:45 浏览: 16
在这段代码中,`cmp` 是一个函数对象,用于比较两个 `Employee` 对象的大小。而在 `max` 函数中,通过 `cmp(*m, *first)` 调用函数对象进行比较,需要使用指针解引用得到对象的值,然后传入函数对象进行比较。这里的 `*m` 和 `*first` 都是 `Employee` 对象,所以需要使用指针解引用得到对象的值,然后才能传入函数对象进行比较。
相关问题
class MyCriterion { public: bool operator()(const Employee& e1, const Employee& e2)const { return e1.age < e2.age; } }; template <class Iterator, class C> Iterator max(Iterator first, Iterator last, C cmp) { Iterator m = first; for (++first; first != last; ++first) if (cmp()) //函数对象使用③ 33333333333333333333333333333333333333 m = first; return m; }
这段代码实现了一个模板函数`max`,它接受两个迭代器`first`和`last`,以及一个函数对象`cmp`作为参数。函数对象`cmp`用于比较两个元素的大小,返回`true`表示第一个元素比第二个元素大,否则返回`false`。
在模板函数`max`中,首先将`m`初始化为`first`,然后从`first`开始遍历到`last`,对于每个元素,都使用函数对象`cmp`进行比较,如果当前元素比`m`大,则将`m`更新为当前元素。最终返回`m`。
这段代码还定义了一个函数对象`MyCriterion`,它重载了函数调用操作符`()`,用于比较两个`Employee`对象的年龄大小。在调用`max`函数时,将函数对象`MyCriterion`作为参数传入,从而实现按照年龄大小获取`Employee`对象中年龄最大的那个。
class MyCriterion {public: bool operator()(const Employee& e1,const Employee& e2)const {return e1.age<e2.age;}//排列 }; template <class Iterator,class C> Iterator max(Iterator first,Iterator last,C cmp) { Iterator m=first; for(++first;first!=last;++first) if(cmp (*m,*first))// ③ //函数对象使用 m=first; return m; }解释这段代码
这段代码定义了一个函数对象 MyCriterion,用于比较两个 Employee 对象的年龄大小。然后定义了一个模板函数 max,该函数接受两个迭代器和一个比较函数对象,返回指向范围内最大元素的迭代器。实现过程是先将第一个元素设为最大值,然后遍历整个范围,如果某个元素比当前最大值大,就将该元素设为最大值。在遍历过程中,通过调用 cmp 函数对象进行比较大小,这里使用的是 ③ 处的函数对象。最后返回最大值对应的迭代器。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![hpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)