• <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 閱讀(326) 評論(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小说| 国产福利电影一区二区三区久久久久成人精品综合 | 久久久久无码国产精品不卡| 久久婷婷色综合一区二区| 777午夜精品久久av蜜臀| 久久久久亚洲AV成人网人人网站 | 国产精品99久久久久久董美香| 亚洲国产精品一区二区久久| 久久久久无码国产精品不卡| 久久天天躁狠狠躁夜夜躁2014| 伊人色综合久久| 久久经典免费视频| 色综合合久久天天综合绕视看| 少妇内射兰兰久久| 久久er国产精品免费观看8| 久久婷婷五月综合国产尤物app| 久久精品国产亚洲5555| 中文字幕久久亚洲一区| 久久久久亚洲AV无码麻豆| 亚洲香蕉网久久综合影视| 国产高潮久久免费观看| 97精品伊人久久大香线蕉app| 精品无码久久久久久午夜| 青青草原综合久久大伊人| 久久久久久一区国产精品| 精品一区二区久久| 久久久久亚洲AV片无码下载蜜桃| 色婷婷久久久SWAG精品| 国内精品伊人久久久久影院对白| 亚洲国产另类久久久精品小说 | 久久久久久久波多野结衣高潮| 久久久午夜精品福利内容| 伊人久久免费视频| 色综合久久久久久久久五月| 亚洲欧洲精品成人久久曰影片| 日韩久久久久中文字幕人妻| 嫩草影院久久99| 国产精品免费久久久久电影网| 久久久久国产| 一级做a爰片久久毛片免费陪| 国産精品久久久久久久|