• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            C++ Programmer's Cookbook

            {C++ 基礎(chǔ)} {C++ 高級(jí)} {C#界面,C++核心算法} {設(shè)計(jì)模式} {C#基礎(chǔ)}

            函數(shù)對(duì)象

            (轉(zhuǎn))

            函數(shù)指針的一種替代策略是Function object(函數(shù)對(duì)象)。

            函數(shù)對(duì)象與函數(shù)指針相比較有兩個(gè)方面的優(yōu)點(diǎn):首先如果被重載的調(diào)用操作符是inline函數(shù)則編譯器能夠執(zhí)行內(nèi)聯(lián)編譯,提供可能的性能好處;其次函數(shù)對(duì)象可以擁有任意數(shù)目的額外數(shù)據(jù),用這些數(shù)據(jù)可以緩沖結(jié)果,也可以緩沖有助于當(dāng)前操作的數(shù)據(jù)。

            函數(shù)對(duì)象是一個(gè)類,它重載了函數(shù)調(diào)用操作符operator() ,該操作符封裝了一個(gè)函數(shù)的功能。典型情況下函數(shù)對(duì)象被作為實(shí)參傳遞給泛型算法,當(dāng)然我們也可以定義獨(dú)立的函數(shù)對(duì)象實(shí)例。

            來看下面的二個(gè)例子: 比較理解會(huì)更好些:

            #include<vector>
            #include<string>
            #include<iostream>
            #include<algorithm>
            using namespace std;
            class Sum {
            int val;
            public:
            Sum(int i) :val(i) { }

            //當(dāng)在需要int的地方,Sum將自動(dòng)轉(zhuǎn)換為int類型
            //這里是為了方便cout<<Sum的實(shí)例;
            operator int() const { return val; }

            //寫在類中的函數(shù)代碼一般默認(rèn)為內(nèi)聯(lián)代碼
            int operator()(int i) { return val+=i; }
            };

            void f(vector<int> v)
            {
            Sum s = 0; //Sum s = 0等價(jià)于Sum s(0),不等價(jià)于Sum s;s = 0;

            //對(duì)vector<int>中的元素求和
            //函數(shù)對(duì)象被作為實(shí)參傳遞給泛型算法
            s = for_each(v.begin(), v.end(), s);

            cout << "the sum is " << s << "\n";

            //更簡(jiǎn)單的寫法,定義獨(dú)立的函數(shù)對(duì)象實(shí)例
            cout << "the sum is " << for_each(v.begin(), v.end(), Sum(0)) << "\n";
            }


            int main()
            {
            vector<int> v;
            v.push_back(3); v.push_back(2); v.push_back(1);
            f(v);
            system("pause");
            return 0;
            }
            -----------------------------------------------
            #include <iostream>
            #include <list>
            #include <algorithm>
            #include "print.hpp"
            using namespace std;

            // function object that adds the value with which it is initialized
            class AddValue {
              private:
                int theValue;    // the value to add
              public:
                // constructor initializes the value to add
                AddValue(int v) : theValue(v) {
                }

                // the ``function call'' for the element adds the value
                void operator() (int& elem) const {
                    elem += theValue;
                }
            };

            int main()
            {
                list<int> coll;

                // insert elements from 1 to 9
                for (int i=1; i<=9; ++i) {
                    coll.push_back(i);
                }

                PRINT_ELEMENTS(coll,"initialized:                ");

                // add value 10 to each element
                for_each (coll.begin(), coll.end(),    // range
                          AddValue(10));               // operation

                PRINT_ELEMENTS(coll,"after adding 10:            ");

                // add value of first element to each element
                for_each (coll.begin(), coll.end(),    // range
                          AddValue(*coll.begin()));    // operation

                PRINT_ELEMENTS(coll,"after adding first element: ");
            }
            -------------------------------------------------------------------------
            operator()中的參數(shù)為container中的元素
            ---------------------------

            另外的實(shí)例:
            Function Objects as Sorting Criteria

            Programmers often need a sorted collection of elements that have a special class (for example, a collection of persons). However, you either don't want to use or you can't use the usual operator < to sort the objects. Instead, you sort the objects according to a special sorting criterion based on some member function. In this regard, a function object can help. Consider the following example:

               // fo/sortl.cpp
            
               #include <iostream>
               #include <string>
               #include <set>
               #include <algorithm>
               using namespace std;
            
            
               class Person {
                 public:
                   string firstname() const;
                   string lastname() const;
                   ...
               };
            
            
               /* class for function predicate
                * - operator() returns whether a person is less than another person
                */
               class PersonSortCriterion {
                 public:
                   bool operator() (const Person& p1, const Person& p2) const {
                       /* a person is less than another person
                        * - if the last name is less
                        * - if the last name is equal and the first name is less
                        */
                       return p1.lastname()<p2.1astname() ||
                              (! (p2.1astname()<p1.lastname()) &&
                               p1.firstname()<p2.firstname());
                   }
               };
            
            
               int main()
               {
            
                   //declare set type with special sorting criterion
                   typedef set<Person,PersonSortCriterion> PersonSet;
            
                   //create such a collection
                   PersonSet coll;
                   ...
            
            
                   //do something with the elements
                   PersonSet::iterator pos;
                   for (pos = coll.begin(); pos != coll.end();++pos) {
                       ...
                   }
                   ...
               }


            //fo/foreach3.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; //function object to process the mean value class MeanValue { private: long num; //number of elements long sum; //sum of all element values public: //constructor MeanValue() : num(0), sum(0) { } //"function call" //-process one more element of the sequence void operator() (int elem) { num++; //increment count sum += elem; //add value } //return mean value double value() { return static_cast<double>(sum) / static_cast<double>(num); } }; int main() { vector<int> coll; //insert elments from 1 to 8 for (int i=1; i<=8; ++i) { coll.push_back(i); } //process and print mean value MeanValue mv = for_each (coll.begin(), coll.end(), //range MeanValue()); //operation cout << "mean value: " << mv.value() << endl; }

            posted on 2005-12-14 16:53 夢(mèng)在天涯 閱讀(4841) 評(píng)論(1)  編輯 收藏 引用 所屬分類: CPlusPlusSTL/Boost

            評(píng)論

            # re: 函數(shù)對(duì)象 2006-01-10 11:55 shanzy

            Function object(函數(shù)對(duì)象)

            個(gè)人覺得應(yīng)該叫:“功能對(duì)象”更好一點(diǎn),JJHOU叫“仿函數(shù)”只是說它用起來像函數(shù)  回復(fù)  更多評(píng)論   

            公告

            EMail:itech001#126.com

            導(dǎo)航

            統(tǒng)計(jì)

            • 隨筆 - 461
            • 文章 - 4
            • 評(píng)論 - 746
            • 引用 - 0

            常用鏈接

            隨筆分類

            隨筆檔案

            收藏夾

            Blogs

            c#(csharp)

            C++(cpp)

            Enlish

            Forums(bbs)

            My self

            Often go

            Useful Webs

            Xml/Uml/html

            搜索

            •  

            積分與排名

            • 積分 - 1804159
            • 排名 - 5

            最新評(píng)論

            閱讀排行榜

            久久九九久精品国产| 国产99久久久久久免费看| 一级a性色生活片久久无| 欧美精品丝袜久久久中文字幕 | 久久91这里精品国产2020| 久久人人爽人人澡人人高潮AV| 亚洲国产精品嫩草影院久久| 久久人与动人物a级毛片| 成人免费网站久久久| 久久成人小视频| 久久免费精品视频| 久久狠狠爱亚洲综合影院| 99久久精品免费| 久久精品国产亚洲AV麻豆网站| 国产精品日韩欧美久久综合| 精品一二三区久久aaa片| 国产精品美女久久久久AV福利| 97视频久久久| 国产免费福利体检区久久| 色综合久久久久无码专区| 婷婷久久综合九色综合九七| 久久91精品久久91综合| 无码人妻久久一区二区三区| 久久精品国产只有精品66| 国产精品久久网| 一本久久a久久精品亚洲| 一本久久a久久精品综合香蕉| 91亚洲国产成人久久精品网址| 色婷婷久久综合中文久久蜜桃av| 久久亚洲中文字幕精品一区四| 久久久九九有精品国产| 国产精品久久久久影院色| 精品久久8x国产免费观看| 久久久久国产精品熟女影院| 97精品伊人久久久大香线蕉| 亚洲欧美久久久久9999| 国产香蕉久久精品综合网| 综合久久久久久中文字幕亚洲国产国产综合一区首 | 一本一道久久综合狠狠老| 婷婷久久综合九色综合绿巨人| 久久久久黑人强伦姧人妻|