• <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>
            posts - 12, comments - 4, trackbacks - 0, articles - 36

            函數對象

            Posted on 2005-12-14 18:24 inwind 閱讀(320) 評論(0)  編輯 收藏 引用 所屬分類: C++學習

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

            函數對象與函數指針相比較有兩個方面的優點:首先如果被重載的調用操作符是inline函數則編譯器能夠執行內聯編譯,提供可能的性能好處;其次函數對象可以擁有任意數目的額外數據,用這些數據可以緩沖結果,也可以緩沖有助于當前操作的數據。

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

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

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

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

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

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

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

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

            //更簡單的寫法,定義獨立的函數對象實例
            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()中的參數為container中的元素
            ---------------------------

            另外的實例:
            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; }
            99久久精品免费| 欧美精品一本久久男人的天堂| 久久精品九九亚洲精品天堂| 中文字幕日本人妻久久久免费| 亚洲欧美一区二区三区久久| 久久99热这里只有精品国产 | 久久精品人人做人人爽电影| 久久精品99久久香蕉国产色戒 | 亚洲午夜无码久久久久小说| 四虎影视久久久免费观看| 国产精品免费久久| 久久久无码精品午夜| 无码乱码观看精品久久| 无码精品久久一区二区三区 | 亚洲欧美日韩久久精品第一区 | 精品久久久久中文字幕日本| 久久久久亚洲AV无码网站| 99久久婷婷国产综合亚洲| 热久久国产精品| 色综合久久天天综线观看| AV无码久久久久不卡蜜桃| 久久青青草原精品国产| 99久久国产热无码精品免费久久久久| 久久99热国产这有精品| 久久一区二区三区99| 久久影院综合精品| 99久久精品久久久久久清纯| 亚洲欧美成人久久综合中文网 | 久久精品亚洲一区二区三区浴池| 久久国产精品77777| 久久人人爽人人澡人人高潮AV | 国产精品久久免费| 青春久久| 亚洲欧美日韩精品久久| 国产精品久久久久久久app| 国产精品久久久久久久久鸭| 久久久久99精品成人片| av国内精品久久久久影院| 亚洲欧美精品一区久久中文字幕| 亚洲中文字幕久久精品无码喷水| 国产精品久久久天天影视香蕉|