之前項目中用到學習了一下,今天總結總結
bind生成一個仿函數,可以配接任意函數(裸函數,類成員函數,靜态成員函數)指定參數傳遞方式個數。在需要仿函數的地方(accumulate,for_each等)超級好用
#include <iostream>
#include <algorithm>
#include <numeric>
#include <map>
#include <vector>
#include <boost/bind.hpp>
using namespace std;
struct comp {
pair<double, double> operator()(const pair<double, double>& init, double x) const {
return make_pair(init.first + x, init.second + x*x);
}
};
class A {
public:
pair<double, double> sum(const pair<double, double>& init, double x) const {
return make_pair(init.first + x, init.second + x*x);
}
};
pair<double, double> sum(const pair<double, double>& init, double x, double y, double z) {
return make_pair(init.first + x + y, init.second + x*x);
}
pair<double, double> sum2(const pair<double, double>& init, double x, double y) {
return make_pair(init.first + x + y, init.second + y*y);
}
int main () {
vector<double> test;
for(int i = 0; i < 100; ++i) {
test.push_back(i);
}
A a;
double y = 0.0;
//a.sum(); A::sum(*this)
//pair<double, double> re = accumulate(test.begin(), test.end(), make_pair(0, 0), comp());
//pair<double, double> re = accumulate(test.begin(), test.end(), make_pair(0, 0), boost::bind((&A::sum), &a, _1, _2));
pair<double, double> re = accumulate(test.begin(), test.end(), make_pair(0, 0), boost::bind(sum, _1, _2, y, y));
//pair<double, double> re2 = boost::bind(sum, _1, _2, y, y)(make_pair(10, 10), 10);
pair<double, double> re2 = boost::bind(sum2, _1, y, _2)(make_pair(10, 10), 10);
// operator+(_1, _2);
cout << re2.first << " " << re2.second << endl;
cout << re.first << " " << re.second << endl;
return 0;
}
boost多線程可以三行代碼搞定。。。bind的使用使得參數傳遞比c語言的不知道友善多少倍
上代碼
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
using namespace std;
boost::mutex mtx;
void show(int i) {
boost::unique_lock< boost::mutex > lock(mtx);//構造函數鎖,析構函數解鎖
//mtx.lock();
cout << "wangbing" << i << endl;
//mtx.unlock();
}
int main() {
int thread_num = 8;
boost::thread_group group;
for(int i = 0; i < thread_num; ++i) {
group.create_thread( boost::bind(show, i));
}
cout << "xxxxxx" << endl;
group.join_all();
return 0;
}