您的位置:首页 > 大数据 > 人工智能

函数对象与 for_each结合使用

2012-05-10 11:06 477 查看
简单使用for_each

//程序1

#include <algorithm>

#include <iostream>

#include <set>

#include <string>

using namespace std;

set<string> Setstr;

void Show(string sr)

{

    cout <<" "<< sr.c_str() << endl;

}

int main(int argc, char * argv[])

{

    Setstr.insert("abd");

    Setstr.insert("123a");

    Setstr.insert("abd");

  for_each(Setstr.begin(), Setstr.end(), Show);

 

   system("pause");

   return 0;

}

 

此程序1:应用到3点:             

1)for_each 第三个参数是函数指针,只需要一个函数名/函数指针。

2)函数指针的 参数默认与前面的两个参数的解引用/ 实际值有关;

 3) set可以添加同一个键,但是会被相同的覆盖掉;同理:map;

 

///程序2

#include <iostream>

#include <list>

#include <algorithm>

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;

    }

};

void f(int i)

{

    cout << i << endl;

}

int main()

{

    list<int> coll;

    // insert elements from 1 to 9

    for (int i=1; i<=9; ++i) {

        coll.push_back(i);

    }

    cout << "initialized:                "<< endl;

    for_each(coll.begin(), coll.end(),       f);  // range   遍历输出

  

    // add value 10 to each element

    for_each (coll.begin(), coll.end(),    // range

        AddValue(10));               // operation

    //第一次遍历时候为   AddValue(10)(*coll.begin())

     cout << "after adding 10::                "<< endl;

     for_each(coll.begin(), coll.end(),    // range

         f);

    // 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: ");

    cout <<"after adding first element:"<< endl;

    for_each(coll.begin(), coll.end(),    // range

        f);

    system("pause");

}

 

//程序3

 

#include <algorithm>

#include <iostream>

#include <set>

#include <string>

#include <map>

using namespace std;

map <int ,int> mapInt;

void f(pair<int, int> p)

{

    cout << p.first<< " "<< p.second << endl;

}

int main(int argc, char * argv[])

{

    int i = 0;

    mapInt.insert(make_pair(i, i));

    i = 1;

    mapInt.insert(make_pair(i, i));

    i = 0;

    mapInt.insert(make_pair(i, i));

    for_each(mapInt.begin(), mapInt.end(), f);

    system("pause");

    return 0;

}

 

 

//程序3:可以看到如何使用 pair类型

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息