• <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++ 高級} {C#界面,C++核心算法} {設(shè)計(jì)模式} {C#基礎(chǔ)}

            函數(shù)對象

            (轉(zhuǎn))

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

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

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

            來看下面的二個例子: 比較理解會更好些:

            #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將自動轉(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;

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

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

            //更簡單的寫法,定義獨(dú)立的函數(shù)對象實(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 夢在天涯 閱讀(4842) 評論(1)  編輯 收藏 引用 所屬分類: CPlusPlusSTL/Boost

            評論

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

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

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

            公告

            EMail:itech001#126.com

            導(dǎo)航

            統(tǒng)計(jì)

            • 隨筆 - 461
            • 文章 - 4
            • 評論 - 746
            • 引用 - 0

            常用鏈接

            隨筆分類

            隨筆檔案

            收藏夾

            Blogs

            c#(csharp)

            C++(cpp)

            Enlish

            Forums(bbs)

            My self

            Often go

            Useful Webs

            Xml/Uml/html

            搜索

            •  

            積分與排名

            • 積分 - 1804603
            • 排名 - 5

            最新評論

            閱讀排行榜

            久久免费美女视频| 久久精品国产亚洲av日韩| 国产精品欧美久久久久无广告| 国产精品毛片久久久久久久| 99久久99久久| 久久久青草青青国产亚洲免观| 色婷婷综合久久久久中文字幕| 亚洲欧美日韩中文久久| 久久这里只精品国产99热| 久久这里的只有是精品23| 久久婷婷五月综合色高清| 国产精品女同一区二区久久| 欧美伊人久久大香线蕉综合 | 欧美成人免费观看久久| 少妇久久久久久被弄高潮| 久久国产成人| 久久91精品国产91久久小草| 人妻系列无码专区久久五月天| 久久久av波多野一区二区| 无夜精品久久久久久| 久久99精品久久久久久| 18岁日韩内射颜射午夜久久成人| 伊人热人久久中文字幕| 久久婷婷成人综合色综合| 欧美亚洲国产精品久久高清 | 国产精品成人久久久| 国产成人AV综合久久| www久久久天天com| 久久精品国产亚洲AV无码娇色| 中文字幕亚洲综合久久菠萝蜜| 国产一区二区精品久久凹凸| 久久精品国产精品国产精品污| 色欲综合久久躁天天躁蜜桃| 久久婷婷五月综合国产尤物app | 久久久久亚洲AV片无码下载蜜桃| 亚洲国产精品综合久久网络| 精品久久久久久无码中文字幕| 国产精品99久久不卡| 99久久精品免费看国产一区二区三区 | 精品久久久无码人妻中文字幕豆芽| 久久国产欧美日韩精品|