• <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; }
            天天久久狠狠色综合| 国产精品免费久久久久电影网| 久久久久亚洲AV无码专区网站| 久久精品国产99久久丝袜| 日本加勒比久久精品| 99精品久久精品一区二区| 国产成人久久精品激情 | 亚洲AV无码久久| 久久伊人精品青青草原高清| 久久香蕉国产线看观看猫咪?v| 久久精品国产99久久久古代| 国产精品久久久久久福利漫画| 久久久WWW免费人成精品| 日产精品久久久久久久性色| 99久久国产综合精品成人影院| 久久夜色精品国产亚洲| 国产91久久综合| 人妻丰满AV无码久久不卡| 久久无码AV中文出轨人妻| 久久96国产精品久久久| 中文字幕乱码人妻无码久久| 国产女人aaa级久久久级| 99久久人妻无码精品系列 | 午夜福利91久久福利| 99久久免费国产精精品| 久久99久久99精品免视看动漫| 久久久久黑人强伦姧人妻| 伊人久久免费视频| 成人免费网站久久久| 久久AV高清无码| 久久久精品人妻一区二区三区四| 要久久爱在线免费观看| 亚洲国产成人久久一区久久| 精品久久久久一区二区三区| 国产欧美一区二区久久| 97久久超碰国产精品2021| 久久亚洲中文字幕精品有坂深雪| 久久人做人爽一区二区三区| 综合久久一区二区三区| 久久婷婷五月综合色奶水99啪| 伊人久久大香线蕉综合5g|