#include <iostream>
#include <algorithm>
using namespace std;
bool myfn(int i, int j) { return i<j; }
int main () {
int myints[] = {3,7,2,5,6,4,9};
// using function myfn as comp:
cout << "The smallest element is " << *min_element(myints,myints+7,myfn) << endl;
cout << "The largest element is " << *max_element(myints,myints+7,myfn) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
考虑到上面的代码,有什么不同,如果我们通过myfn或&myfn到 min_element?当我们试图传递一个更为标准的仿函数?
通常,pass-by-reference和pass-by-value仅指传递变量,而不是函数.(模板函数引入了一些复杂性,但这是另一个讨论.)在这里,您将myfn作为指向函数的指针传递.如果您使用&myfn相反没有区别.编译器将隐式转换myfn为指向具有该名称的函数的指针.
| 归档时间: |
|
| 查看次数: |
303 次 |
| 最近记录: |