您的位置:首页 > 其它

std::unary_function 和 std::binary_function.

2012-11-14 01:01 267 查看
要将书写函数对象的进程简单化, 标准库提供两个类模板作为这样的对象的基类:                 std::unary_function 和 std::binary_function. 它们都在头文件 < functional > 中声明. 根据其命名, unary_function 提供接收一个参数的基函数而 binary_function 提供一个接收两个参数的基函数.unary_function:定义类型能由派生类继承提供一元求函数对象的空的基本结构。
template<class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
备注模板结构作为一个基。对于定义窗体 result_typeoperator()的选件类(constargument_type&const的成员函数。当 argument_type 及其返回类型为 result_type,所有此类派生的一元"功能可以引用自己唯一的参数类型。示例
// functional_unary_function.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>

using namespace std;

// Creation of a user-defined function object
// that inherits from the unary_function base class
class greaterthan10: unary_function<int, bool>
{
public:
result_type operator()(argument_type i)
{
return (result_type)(i > 10);
}
};

int main()
{
vector<int> v1;
vector<int>::iterator Iter;

int i;
for (i = 0; i <= 5; i++)
{
v1.push_back(5 * i);
}

cout << "The vector v1 = ( " ;
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << *Iter << " ";
cout << ")" << endl;

vector<int>::iterator::difference_type result1;
result1 = count_if(v1.begin(), v1.end(), greaterthan10());
cout << "The number of elements in v1 greater than 10 is: "
<< result1 << "." << endl;
}
<span id="mt4" class="sentence" data-guid="b44318f795d162c9e90b8f41bc887435" data-source="" the="" vector="" v1="(" 0="" 5="" 10="" 15="" 20="" 25="" )"="" xml:space="preserve">
这个矢量v1 = (0 5 10 15 20 25)元素数大于v1的大于10是:3.
要求标头: <functional>命名空间: std
binary_function:说明如何在 Visual C++ 中使用 (STL)标准模板库 (stl) 中 binary_function 结构。
template<class _A1, class _A2, class _R>struct binary_function{typedef _A1 first_argument_type;typedef _A2 second_argument_type;typedef _R result_type;};
备注
 说明
类/参数名在原型不匹配版本在头文件。 修改某些提高可读性。
binary_functionA,B,C 类用于,如果基类允许用户轻松地定义采用数据类型 A 和 B 作为参数并返回数据类型 C 对象的二元运算符函数。示例
// binfunc.cpp// compile with: /EHsc//// Structure used: binary_function<A,B,C> - base//                 class used to create operator//                 functions taking data types A//                 and B and returning data type C.#include <functional>#include <iostream>using namespace std ;class binary_test : public binary_function<binary_test &,int,float>{public:float value;binary_test(){value=10.0;}binary_test(float x){value=x;}result_type operator<<(second_argument_type arg2);};binary_test::result_typebinary_test::operator<<(binary_test::second_argument_type arg2){value = (float)(((int)value) << arg2);cout << "New value after shift is " << value << endl;return value;}int main(void){binary_test item;cout << "Begin" << endl;item = item << 2;}
Output
BeginNew value after shift is 40
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: