使用boost的bind

来源:互联网 发布:suse防火墙开放端口 编辑:程序博客网 时间:2024/05/17 21:56
#include <algorithm>#include <map>#include <iostream>#include "boost/bind.hpp"using namespace std;void printPair(const pair<int, int>& elem){  cout << elem.first << "->" << elem.second << endl;}class Test {public:Test() {  myMap.insert(make_pair(4, 40));  myMap.insert(make_pair(5, 50));  myMap.insert(make_pair(6, 60));  myMap.insert(make_pair(7, 70));  myMap.insert(make_pair(8, 80));}void printResult() {  int a = 10;  //using static method with two argument  for_each(myMap.begin(), myMap.end(), boost::bind(&Test::printPair, _1, a));   //using static method with one argument  for_each(myMap.begin(), myMap.end(), boost::bind(&Test::printPair2, _1));   //using instance method  for_each(myMap.begin(), myMap.end(), boost::bind(&Test::printPair3,  boost::ref(*this), _1)); }static void printPair(const pair<int, int>& elem, int a){  cout << elem.first << "->" << elem.second << ";a=" << a << endl;}static void printPair2(const pair<int, int>& elem){  cout << elem.first << "2->" << elem.second <<  endl;}void printPair3(const pair<int, int>& elem){  cout << elem.first << "3->" << elem.second <<  endl;}private:  map<int, int> myMap;};int f(int a, int b) {    return a - b;}int main(int argc, char** argv){  map<int, int> myMap;  myMap.insert(make_pair(4, 40));  myMap.insert(make_pair(5, 50));  myMap.insert(make_pair(6, 60));  myMap.insert(make_pair(7, 70));  myMap.insert(make_pair(8, 80));  for_each(myMap.begin(), myMap.end(), &printPair);   Test t;  t.printResult();  //using bind create a new method then call it with 1  int c = boost::bind(f, _1, 2)(1);   std::cout << "c:" << c << endl;  c = boost::bind(f, 10, _1)(1);   std::cout << "c:" << c << endl;  //exchange the argument  c = boost::bind(f, _2, _1)(1, 2);   std::cout << "c:" << c << endl;  return (0);}
0 0
原创粉丝点击